Jj Del Carpio

Jj's web stream

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 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 &#39;error&#39; class if there&#39;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(&#39;class&#39;, &#39;&#39;)
                    classes += &#39; errors&#39;
                    self.fields[f_name].widget.attrs[&#39;class&#39;] = 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

#369647" title="2011-04-03 18:39:00">Jon: Why not just iterate of self.errors?

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

#370520" title="2011-06-05 13:19:00">DuĊĦan Maliarik: handy. thanks

#371222" title="2012-09-21 00:09:00">Jj: 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.

#371225" title="2012-09-28 22:22:00">Sahas Katta: Thanks again, I'm digging into this further.

Jj Avatar of Jj

Reply or react to this post via Webmentions