Dunski
Dunski

Reputation: 672

How can I avoid form.is_valid() flagging an empty field as an error in Django?

I have a template that is used for updating a table. However, the user can choose to update one field or all of them. The chances are that he won't be updating all the fields, so I want to be able to run form.is_valid(), but I don't want to have it return false if there are empty fields in the form which there will almost certainly be.

I don't want to use required=False in the form, because there is another template that uses the same form where the user must fill in almost all the fields.

Upvotes: 2

Views: 1542

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

The simplest thing to do would probably be to subclass your form and set required=False in the subclass, either repeating the field definition or doing it in __init__. Otherwise, you could set required=False in your view, eg:

def some_view(request):
    if request.METHOD == 'POST':
        form = SomeFormClass(request.POST)
        form.fields['fieldname'].required = False
        if form.is_valid():
            # etc

Upvotes: 6

Related Questions