Dynamically change field attributes in a Django ModelForm

I’ve encountered situations using Django’s ModelForm where I’ve needed the form to validate differently then the default behavior in various instances. Here’s an example of how I changed all the fields from the default of not being required to all being required without much effort:

class AddressRequiredForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AddressForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.iteritems():
            if name not in ['address2',]:
                field.required = True

    class Meta:
        model = Address

This is pretty simple, but it saved me a lot of time by not having to re-type each field name with a new set of properties.

Add post to:   Delicious Reddit Slashdot Digg Technorati Google
Make comment

Comments

No comments for this post

Required. 30 chars of fewer.

Required.

captcha image Please, enter symbols, which you see on the image