我在Django中有一个表单,它根据所选人群(用于发送消息)生成复选框中的人物名称
class MessageForm(forms.Form):
people = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple())
message = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'style': 'width: 100%; height: 150px;'}))
def __init__(self, people_list, *args, **kwargs):
super(MessageForm, self).__init__(*args, **kwargs)
self.fields['people'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=people_list)
当我把它放在模板视图中时
return render(request, 'test.html', {'form': MessageForm(people)})
它在表单中呈现选定的人。但我的问题是如何验证该表单,因为
form = MessageForm(request.POST, people_list=people)
或
form = MessageForm(people_list=people, request.POST)
当我想验证像这样的表单时,会出错
if form.is_valid():
如何正确地做到这一点?
答案 0 :(得分:2)
form = MessageForm(people, data=request.POST)
会这样做。
但是你不应该改变形式init的签名。你应该使people_list
成为一个kwarg,以便将request
保留为第一个位置arg:
def __init__(self, *args, **kwargs):
people_list = kwargs.pop('people_list', None)
super(MessageForm, self).__init__(*args, **kwargs)