Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "class Meta" is necessary while creating a model form?

from django import forms
from .models import NewsSignUp

class NewsSignUpForm(forms.ModelForm):
    class Meta:
        model = NewsSignUp
        fields = ['email', 'first_name']
here

This code works perfectly fine. But, when I remove "class Meta:" as below, it throws a ValueError saying "ModelForm has no model class specified."

from django import forms
from .models import NewsSignUp

class NewsSignUpForm(forms.ModelForm):
    model = NewsSignUp
    fields = ['email', 'first_name']

Can someone please give an explanation? :(

like image 485
UtkarshPramodGupta Avatar asked Sep 13 '16 18:09

UtkarshPramodGupta


1 Answers

You are creating a ModelForm subclass. A model form has to have a model to work from, and the Meta object configures this.

Configuration like this is grouped into the Meta class to avoid name clashes; that way you can have a model field in your form without that interfering with the configuration. In other words, by using class Meta: you get a nested namespace used just to configure the ModelForm in relation to the model.

The namespace for the ModelForm class body itself then (outside Meta) is reserved for the form fields themselves, as well as form methods. You'd normally just let ModelForm generate those fields from your model, but you can, in principle, add fields to this. Another reason to put fields in the class is to completely replace any of the generated fields with your own version.

From the Model Forms documentation:

ModelForm is a regular Form which can automatically generate certain fields. The fields that are automatically generated depend on the content of the Meta class and on which fields have already been defined declaratively. Basically, ModelForm will only generate fields that are missing from the form, or in other words, fields that weren’t defined declaratively.

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

Because ModelForm expects the configuration to be set under the Meta name, you can't just remove that and put model and fields in the ModelForm class itself; that's just the wrong place.

like image 118
Martijn Pieters Avatar answered Nov 16 '22 02:11

Martijn Pieters