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 '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
#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.