Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style Django form error message

I'm trying to make django form defa error red and bold. For example, make "This field is required" red and bold. I saw error_css_class = 'error' but it's not working. https://docs.djangoproject.com/en/1.5//ref/forms/api/#django.forms.Form.error_css_class Thank you! This is my models.py

class RegiForm(forms.Form):
    error_css_class = 'error'
    DateInput = partial(forms.DateInput, {'class': 'datepicker'})
    email = forms.EmailField(max_length=75)
    first_name = forms.CharField(max_length=25)
    last_name = forms.CharField(max_length=25)
    address = forms.CharField(max_length=200)

This is my template:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>RegistrationForm</title>
    </head>
    <body>
        <h1>Registration Form</h1>
        <form action="/login/regi/" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
like image 279
Penocky Avatar asked Sep 14 '26 18:09

Penocky


2 Answers

Just add this CSS to change error message color:

.errorlist {
    color: red;
}

or if you want to change field border color then

.error input, .error select {
    border: 2px red solid;
}
like image 121
Ratna Halder Avatar answered Sep 16 '26 08:09

Ratna Halder


I know this is an old question but I needed it as a beginner.

You can extend the ErrorList class in the

django.forms.utils

to style it as you wish. In my case I wanted it as divs and Bootstrap alerts.

So I did this in forms.py

class DivErrorList(ErrorList):
    def __str__(self):
        return self.as_divs()

    def as_divs(self):
        if not self:
            return ''
        return '<div class="errorlist">%s</div>' % ''.join(['<div class="error alert alert-danger mt-1">%s</div>' % e for e in self])

and in the views.py

form = AddToCartForm(error_class=DivErrorList)

see the documentaion: customizing-the-error-list-format

like image 23
AtharvaCM Avatar answered Sep 16 '26 08:09

AtharvaCM