How to "stop" validation when having errors (is_valid) for form?

15 views
Skip to first unread message

gengsh...@gmail.com

unread,
Sep 11, 2015, 2:51:50 AM9/11/15
to Django users
Example: I have 2 <input> on a html page, which is a form (assume it is login form, with username and password, both are required and will do validation on this.).

The behavior of is_valid I see is:
When submit, the returned errors for the form are:
This field is required (for username) 
This field is required (for password)
We'll usually render these messages for the fields (example: {{ form }} will automatically do all these).

Now, my question is, it seems like is_valid will trigger validation on both username and password every time? How to stop it in case one field cannot pass the validation? Does it make sense to validate all these always? I think in some of web pages, the behaviour we see is, when one field does not fulfill the requirements, it give an error message for this only, and when user submit again but the next field does not fulfill the requirement, it give error for this field.

Current behaviour in django:
user name: .....(input box)
password: ....(input box)
Submit without any value, we get:
user name: .....(input box)             This field is required
password: ....(input box)                This field is required

I expect:
user name: .....(input box)             This field is required
password: ....(input box)                (No error here)

If username is entered and password is empty, submit again, we'll get:
user name: what you enter here (input box)             
password: ....(input box)               This field is required

Any idea how to achieve this?

Thanks,
Shenghong

Tom Evans

unread,
Sep 11, 2015, 9:47:50 AM9/11/15
to django...@googlegroups.com
"required" means "always required", but you wish to only have the
password required when the username is also provided.

Therefore, set password as not required, and add a check in clean()
that applies your special logic and assigns the error message to the
appropriate field.

Eg:

def clean(self):
data = super(MyForm, self).clean()
user = data.get('username')
password = data.get('password')
if user and not password:
self.add_error('password', 'This field is required')

See also:

https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages