Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing Django ModelForms

Tags:

django

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?

like image 455
AlexBrand Avatar asked Jun 07 '12 19:06

AlexBrand


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is class Meta in Django forms?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.


1 Answers

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.

like image 175
Ghopper21 Avatar answered Oct 01 '22 21:10

Ghopper21