解决方法一:重写构造方法(推荐)
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