我有一个模型选择字段(多对多关系),当我尝试提交表单时会抛出错误Select a valid choice. That choice is not one of the available choices.
我还添加了forms __init__
,但仍面临同样的错误。我认为错误是由于复选框值中的字符串,整数。任何人都可以帮我解决这个问题。在这里发布我的代码
class CustomSignupForm(forms.ModelForm):
telephone = forms.CharField(label=_('Telephone'), required=False)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(CustomSignupForm, self).__init__(*args, **kwargs)
self.fields['categories'] = forms.ModelChoiceField(queryset=Category.objects.filter(status=True), widget=forms.CheckboxSelectMultiple)
for name, field in self.fields.iteritems():
attr = {'class': 'custom-class'}
if field.label:
attr['placeholder'] = field.label
field.widget.attrs.update(attr)
类别是具有多对多选择的字段,不允许我提交表单。
模型
class Category(DateUpdate):
title = models.CharField(max_length=256,null=True,blank=False)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.title
表格
<div class="form-group">
<label>
{{ form.categories.label }}
</label>
{% for check_choice in form.categories %}
{{ check_choice.tag }}
{{check_choice.choice_label}}
{% endfor %}
{% if form.categories.errors %}
<span class="error">
{{ form.categories.errors.as_text }}
</span>
{% endif %}
</div>