在formset中设置auto_id,不要在第一次显示时禁用错误

时间:2017-02-26 08:07:38

标签: python django django-forms

我正在撰写以下表格的观点:

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_iduse_required_attribute如何设置更优雅?

1 个答案:

答案 0 :(得分:1)

  • 表单始终绑定,因此表单无效。我以超级电话(super().__init__(*args, **kwargs)
  • 的形式忘记了asterik
  • 上述解决方案之后,验证也有效
  • formset还默认禁用了auto_id属性和use_required_attribute:

    question_form.auto_id = False
    choice_form_set.auto_id = False
    question_form.use_required_attribute = False