[Answer]-Required and Optional Field in Django Formset

1👍

Django formset in this case works in a peculiar way – forms without data have empty cleaned_data but treated as valid. So you have to manually check existence of form data:

# at imports section of views.py
from django.forms.util import ErrorList

# at addname()
actual_data = []
for form in data:
    firstname = form.get('first_name')
    lastname = form.get('last_name')
    if firstname and lastname:
        webform (firstname, lastname, location)
        actual_data.append(form)
if actual_data:
    context = {'data': actual_data, 'location': location}
    return render(request, 'nameform/success.html', context)
formset._non_form_errors = ErrorList(['Enter at least one person name.'])

0👍

you need to inherit from BaseFormSet and override “clean” method to implement manual validation .

the django docs has an example : https://docs.djangoproject.com/en/1.7/topics/forms/formsets/#custom-formset-validation

Leave a comment