Alex Rivera | Logout

Subclassing Django ModelForms

Asked 2012-06-07T19:23:36.273
19

I want to extend ModelForms with the main purpose of adding fields to the form. I think it is easier to see with an example:

# Basic listing
class BasicForm(ModelForm):
    class Meta:
        model = Business
        fields = ('category', 'city', 'name', 'address', 
                'slogan', 'phone', 'website', 'email')

class SocialForm(BasicForm):
    class Meta:
        model = Business
        fields = ('facebook','twitter')

Would that even work? Or would it just wipe out the other fields from BasicForm in SocialForm?

What is the correct way of doing this?

Edit
Report

1 Answer

47

This is a late answer, but I wanted to note that you can subclass the inner Meta class like this:

class SocialForm(BasicForm):
    class Meta(BasicForm.Meta):
        fields = BasicForm.Meta.fields + ('facebook', 'twitter')

That way you don't have to repeat the model = Business definition, and any other Meta attributes you may add to BasicForm will automatically be inherited by SocialForm.

For reference, here's the Django documentation on this approach.

answered 2012-09-02T03:22:41.390

Your Answer