开发者

Identify the nature of field error in django forms

The 2 types of validation error a form field in django can have are 'required' and 'invalid'. Is there any way to find out which of these two errors has happened, from the template? Something like

{% if form.username.errors %}
{% for error in form.username.errors %}
{% if error.required %}
Please enter the u开发者_如何学编程sername
{% else %}
{{ error }}
{% endif %}

I just want to override the error message for the 'required' error, i.e., I want to display my own error message if that error happens. I am using django.contrib.auth.views which uses django.contrib.auth.forms.AuthenticationForm which I don't want to try customizing.


Hope you are searching for this type of handle in html template

{% for x in form.errors %}
    {%if "__all__" in x %}
        Wrong username and password
    {%else%}
        {%if "username" in x %}
            Requires username
            <br>
        {%endif%}
        {%if "password" in x %}
            Requires Password
            <br>
        {%endif%}
    {%endif%}
{%endfor%}

Messages will be printed like this on your login page

Requires username Requires Password

Wrong username and password


You really should just override the Authentication form. The view accepts an argument that allows for you to override form easily.

I think something like this should work:

All you need to do is override the clean_username method like so: edit:

overriding the clean_username method fails to change the validation error message because of the following from the form and field validation docs:

  • The clean() method on a Field subclass. This is responsible for running to_python, validate and run_validators in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError, the validation stops and that error is raised. This method returns the clean data, which is then inserted into the cleaned_data dictionary of the form.

  • The clean_<fieldname>() method in a form subclass – where is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).

The Field subclass is validated first and returns the cleaned data that is used for the clean_<field_name>() method. If an error occurs there the validation of that field stops.

This means that to override the message you need to either override the Field validation or make the field not require a value so no validation error is raised at that step and raise a required method in the clean_<fieldname>() method

>>> from django.contrib.auth.forms import AuthenticationForm
>>> class MyAuthForm(AuthenticationForm):
...     def __init__(self, *args, **kwargs):
...         super(MyAuthForm, self).__init__(*args,**kwargs)
...         self.fields['username'].error_messages['required']='Custom Required Msg'
... 
>>> form = MyAuthForm(data={'password':'asdf'})
>>> form.is_valid()
False
>>> form.errors
{'username': [u'Custom Required Msg']}
>>> 

urls.py

from someapp.forms import MyAuthForm

urlpatterns = patterns('',
    ...
    (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'someapp/login.html', 'authentication_form':MyAuthForm, }),
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜