Django formset doesn't validate

别等时光非礼了梦想. 提交于 2019-11-30 13:27:36
mpen

Heh, I was having this exact same problem. The problem is that you're using a formset!! Formsets allow all fields in a form to be blank. If, however, you have 2 fields, and fill out only one, then it will recognize your required stuffs. It does this because formsets are made for "bulk adding" and sometimes you don't want to fill out all the extra forms on a page. Really annoying; you can see my solution here.

For each of the fields that are required, add an extra entry in the attrs parameter


    resident_status = forms.ChoiceField(widget=forms.Select(
        attrs={'class': 'form-control', 'required': 'required'}), choices=President.RESIDENT_STATUS,
        required=True)



As you can see, I maintain the required=True for django's form validation but specify 'required':'required' for the template to insist for the field be required.

Hope that helps.

Add 2 lines.

if request.method == 'POST':
  def initial_form_count(self): return 10 # the number of forms
  AlbumFormSet.initial_form_count = initial_form_count
  formset = AlbumFormSet(request.POST, request.FILES)

Good luck!

use:

if not any(formset.errors): ...

instead of:

if formset.is_valid(): ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!