Why "class Meta" is necessary while creating a model form?
<pre><code>from django import forms
from .models import NewsSignUp

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

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

<pre><code>from django import forms
from .models import NewsSignUp

class NewsSignUpForm(forms.ModelForm):
    model = NewsSignUp
    fields = ['email', 'first_name']
</code></pre>

<p>Can someone please give an explanation? :(</p>

<p>You are creating a <em><code>ModelForm</code></em> subclass. A model form <strong>has</strong> to have a model to work from, and the <code>Meta</code> object configures this.</p>

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

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

<p>From the <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/" rel="nofollow"><em>Model Forms</em> documentation</a>:</p>

<blockquote>
  <p><code>ModelForm</code> is a regular <code>Form</code> which can automatically generate certain fields. The fields that are automatically generated depend on the content of the <code>Meta</code> class and on which fields have already been defined declaratively. Basically, <code>ModelForm</code> will only generate fields that are missing from the form, or in other words, fields that werenât defined declaratively.</p>
  
  <p>Fields defined declaratively are left as-is, therefore any customizations made to <code>Meta</code> attributes such as <code>widgets</code>, <code>labels</code>, <code>help_texts</code>, or <code>error_messages</code> are ignored; these only apply to fields that are generated automatically.</p>
</blockquote>

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

python django django-models django-forms