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
Jon: Why not just iterate of self.errors?
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?
DuĊĦan Maliarik: handy. thanks
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.
Sahas Katta: Thanks again, I'm digging into this further.