W
W
Wizzy2016-09-12 11:39:59
Django
Wizzy, 2016-09-12 11:39:59

Why are unbound forms not valid in django?

There is a form with initial values ​​specified in initial:
forms:

class UserEditForm(forms.Form):
    sn = forms.CharField(required=True)
    ml = forms.EmailField(required=True)
    mr = forms.EmailField(required=True)

views:
form = UserEditForm(data=request.POST or None, initial={'sn': user.sn, 'ml': user.ml, 'mr': user.mr})

If I understand correctly, this form is called " unbound form ".
What is the correct way to make a POST request to such forms if form.is_valid()it is always False?
+
With a GET request, all fields are displayed correctly.
When a POST request is made, the field values ​​are changed to None.
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2016-09-12
@Wizzy

if you do not pass data to the form or pass None,
then the is_bound flag will be False:
and accordingly the form will always be invalid!

def is_valid(self):
        """
        Returns True if the form has no errors. Otherwise, False. If errors are
        being ignored, returns False.
        """
        return self.is_bound and not self.errors

If you pass as data request.POST or just an empty dictionary, then this will already be a regular form that will be validated according to the form definition.
Also a note about initial , there is a suspicion that you consider it as a default value - if the field is not passed to data, then the value from initial will be taken, and so it doesn’t work like that, initial fields are used when generating the html of the form display, but not during validation .
ZY, code examples from django1.9

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question