Changing how Forms.Validationerror is displayed in Django

Asked

Viewed 174 times

0

It is possible to change the way the ValidationError is displayed? I noticed that the Django creates a tag <ul> and within it a tag <li> error. Can I change the way this is done? And if I want to change the class of these elements, how would I?

I’m trying to do this in the authentication of Django, I took a look at the source code and the django.contrib.auth.forms in form AuthenticationForm(only the part related to the error display) is like this:

 error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),

 def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')

    if username is not None and password:
        self.user_cache = authenticate(self.request, username=username, password=password)
        if self.user_cache is None:
            raise self.get_invalid_login_error()
        else:
            self.confirm_login_allowed(self.user_cache)

    return self.cleaned_data


 def get_invalid_login_error(self):
        return forms.ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'username': self.username_field.verbose_name},
        )

1 answer

0

You can access the list of errors in your template. For example, to create tags h1 with the errors of a field name form:

{% if form.name.errors %}
    {% for error in form.name.errors %}
        <h1 class="header-erro">{{ error }}</h1>
    {% endfor %}
{% endif %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.