On Fri, Sep 11, 2015 at 7:37 AM,  <gengshengh...@gmail.com> wrote:
> 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?
>

"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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAFHbX1JXZNQ2Tw00yxb-hZiOCN6%3D5zm03AECSEj9jDBdVEOt2A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to