title: Add 'error' class to widgets with errors in Django Forms
link: http://jj.isgeek.net/2010/10/add-error-class-to-widgets-with-errors-in-django-forms/
author: Jj
description: 
post_id: 624
date: 2010/10/27 15:33:29
created_gmt: 2010/10/27 20:33:29
comment_status: open
slug: add-error-class-to-widgets-with-errors-in-django-forms

Many times UI requires us to style differently widgets that have errors in a field instead or next to an error message. 

Django provides a nifty[ `.errors`](http://docs.djangoproject.com/en/dev/topics/forms/) attribute to tell if a field of form has errors but you can't affect the rendering of a widget with it. 

And going through all your widgets can be a pain when you only need that ona extra HTML class: 
    
    
    <input type="text" class="errors" name="my_field" id="id_my_field"/>
    

I came up with this dirty snippet that gets the job done: 
    
    
    class MyForm(forms.Form):
        """
        Extend from this form so your widgets have an 'error' class if there's
        an error on the field. 
        """ 
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            if self.errors:
                for f_name in self.fields:
                    if f_name in self.errors:
                        classes = self.fields[f_name].widget.attrs.get('class', '')
                        classes += ' errors'
                        self.fields[f_name].widget.attrs['class'] = classes
    

Now you can either extend from that class or encapsulate in a method, add to all your `__init__` on your forms or whatever.

## Comments

**[Jon](#369647 "2011-04-03 18:39:00"):** Why not just iterate of self.errors?

**[SK](#371221 "2012-09-20 23:51:00"):** How can I get this to work on all my ModelForms and forms.Form without needing to extend each and every one by hand?

**[Dušan Maliarik](#370520 "2011-06-05 13:19:00"):** handy. thanks

**[Jj](#371222 "2012-09-21 00:09:00"):** And then in your code instead of doing `from django import forms`, do `from mymodule import my_forms as forms`, and your code should work as before.

**[Sahas Katta](#371225 "2012-09-28 22:22:00"):** Thanks again, I'm digging into this further.

