19
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? :(

2
  • This post explains better
    – kt14
    Sep 13, 2016 at 18:03
  • @kt14 that's actually not the same: this is focused on generating forms from models, and the linked question is more about metadata within model definitions. Both, I have found, give complementary and largely nonoverlapping views of how Meta is used in Django.
    – eric
    Aug 15, 2017 at 14:24

1 Answer 1

23

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.