Sam Odio's blog has been moved to http://sam.odio.com

You're reading a blog that's no longer maintained. Read why.

Friday, January 23, 2009

Adding custom attributes to django modelform fields

(permalink)
Finding an elegant way to solve a particular problem that's been stumping you for a while is always a nice feeling.

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).


class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
    def __init__(self, *args, **kwargs):
        super(PhotoForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['onClick'] = "this.value =;"


blog comments powered by Disqus

Links to this post:

Create a Link

<< Home