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 username
{% 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.
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 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>()methodurls.py