首页 > 其他 > 详细

数据源数据无法实时更新

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

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

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

数据源数据无法实时更新

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!