[Solved]-Django input element error css class


This can be done completely through your template.

You build the form template for each form field that you want to test you can use the following example construct

<input type="text" class="reg-txt{% if form.fieldname.errors %} errors{% endif %}"/>

This lets you provide the interface you want without modifying the view & django form code.


If you want to place your error CSS class to form input widgets (not their containers), you can derive your form class from the following one:

class StyledErrorForm(forms.Form):
     def is_valid(self):
         result = super().is_valid()
         # loop on *all* fields if key '__all__' found else only on errors:
         for x in (self.fields if '__all__' in self.errors else self.errors):
             attrs = self.fields[x].widget.attrs
             attrs.update({'class': attrs.get('class', '') + ' is-invalid'})
         return result


It’s now easy — new feature in Django 1.2

Just add an attribute on the form class & you’re good to go. This feature is mentioned in the docs under a “new in 1.2” note, but you can find the magic at django.forms.forms.BoundField.css_classes Here’s the API reference, and an example:

class MyForm(forms.Form):
    required_css_class = "required"
    error_css_class = "error"


Using a Custom Template…

Personally never had much luck using the built in Django error classing solutions, and besides, I like to use the built in ‘striptags’ template filter on the errors, to get rid of all the html list stuff which I cant figure out how to render nicely anyway.

I use the following custom template to class them as ‘error_id’.

def error_id(value):
    if value=='':
        return ''
        return r'<span class="error_id">'+value+'</span>'

Render the individual errors in your template using:

{{ form.my_field.errors|striptags|error_id}}

Or render the whole form using something like:

    <table border="1" cellpadding="5px" align="center">
        {% for field in form.visible_fields %}
                        <td> {{ field.label_tag }}: </td>
                        <td>    {{ field }}  </td>
                        <td> {{ field.errors|striptags|error_id }} </td>

        {% endfor %}



(Better late than never)

You should be able to do this with Django Uni Form


Leave a comment