Why “class Meta” is necessary while creating a model form?

这一生的挚爱 提交于 2020-01-13 20:31:49

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/39476334/why-class-meta-is-necessary-while-creating-a-model-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!