我正在撰写以下表格的观点:
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('question_text',)
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
self.fields['question_text'].label = 'Question'
class ChoiceForm(forms.ModelForm):
class Meta:
model = Choice
fields = ('choice_text',)
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
self.fields['choice_text'].label = 'Choice'
ChoiceFormSet = inlineformset_factory(Question, Choice, form=ChoiceForm,
extra=6, validate_min=1, can_delete=False)
def create_question(request):
if request.method == "POST":
question_form = QuestionForm(request.POST)
choice_formset = ChoiceFormSet(request.POST)
if question_form.is_valid() and choice_formset.is_valid():
question = question_form.save()
choice_formset.instance = question
choice_formset.save()
return HttpResponseRedirect(reverse('polls:vote', args=(question.id,)))
else:
question_form = QuestionForm()
choice_formset = ChoiceFormSet()
question_form.auto_id = False
question_form.use_required_attribute = False
for form in choice_formset:
form.auto_id = False
form.use_required_attribute = False
return render(request, 'polls/create.html', {'question_form': question_form, 'choice_formset': choice_formset})
第一次显示视图时,也会显示字段必填错误消息
表单需要填写所有选项,但它应该只有一个:validate_min=1
auto_id
和use_required_attribute
如何设置更优雅?
答案 0 :(得分:1)
super().__init__(*args, **kwargs)
)formset还默认禁用了auto_id属性和use_required_attribute:
question_form.auto_id = False
choice_form_set.auto_id = False
question_form.use_required_attribute = False