R3turnz R3turnz -4 years ago 123
Python Question

Set auto_id in formset and do not disable errors on first display

I am writing the view for following 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})



  • The field required error message is also shown the first time the view is displayed

  • The form requires the fill out all choices but it should only be one:
    validate_min=1

  • How can
    auto_id
    and
    use_required_attribute
    set more elegant?


Answer Source
  • The form was always bound and so the form was invalid. I forgot the asterik in the form super call (super().__init__(*args, **kwargs))
  • After the solution above the validation also worked
  • A formset has also the auto_id property and use_required_attribute disabled by default:

    question_form.auto_id = False
    choice_form_set.auto_id = False
    question_form.use_required_attribute = False
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download