Adding custom attributes to django modelform fields(permalink)
Savraj and I were talking about django's modelforms today. My modelform conversations always seem to gravitate toward lamenting about how it is hard to customize them. That's been a problem that's bothered both of us in the past. My solution was to customize the CSS of the form. This worked for some elements (such as the form's length), but not others. Another solution is to explicitly declare each field with the customized attribute, but this seams to defeat the whole purpose of modelforms.
I just figured out a more flexible solution that I'll share here. It allows me to modify the attributes of a django widget without explicitly declaring the field (which is great). In the example I modify the onclick attribute. You can use it to modify any attribute you want (eg. size, max_length, value, etc).
model = Photo
def __init__(self, *args, **kwargs):
super(PhotoForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['onClick'] = "this.value =;"