码迷,mamicode.com
首页 > 其他好文 > 详细

数据源数据无法实时更新

时间:2017-12-22 00:38:37      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:form   info   inf   self   required   post   elf   实时   efi   

解决方法一:重写构造方法(推荐)

class ClassForm(Form):
	caption = fields.CharField(error_messages={‘required‘:‘班级名称不能为空‘})
	# headmaster = fields.ChoiceField(choices=[(1,‘娜娜‘,)])
	headmaster_id = fields.ChoiceField(choices=[])

	def __init__(self,*args,**kwargs):
		super().__init__(*args,**kwargs)
		self.fields[‘headmaster_id‘].choices = models.UserInfo.objects.filter(ut_id=2).values_list(‘id‘,‘username‘)

  

解决方法二:利用Django自带的类方法

from django.forms.models import ModelChoiceField
class ClassForm(Form):
	caption = fields.CharField(error_messages={‘required‘:‘班级名称不能为空‘})
	# headmaster = fields.ChoiceField(choices=[(1,‘娜娜‘,)])
	headmaster_id = ModelChoiceField(queryset=models.UserInfo.objects.filter(ut_id=2)) #这个是单选的,还有一个是多选的:ModelMultipleChoiceField

  

对于ModelForm:会帮我们判断model中的字段:

  如果是FK:ModelChoiceField

  如果是M2M:ModelMultipleChoiceField

数据源数据无法实时更新

标签:form   info   inf   self   required   post   elf   实时   efi   

原文地址:http://www.cnblogs.com/wangbaihan/p/8082811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!