简体   繁体   中英

What's difference between property and fields of meta in django form?

Curious about their difference. Example :

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

GENDER_CHOICES = (
    ('M', '남'),
    ('F', '여'),
)


class MyUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    birth = forms.DateField(widget=forms.SelectDateWidget(
        years=range(1970, 2015)), required=True)
    gender = forms.ChoiceField(choices=GENDER_CHOICES, initial='M')

    class Meta:
        model = User
        fields = ('username', 'birth', 'email',
                  'gender', 'password1', 'password2')

    def save(self, commit=True):
        user = super(MyUserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.birthday = self.cleaned_data['birth']

        if commit:
            user.save()

        return user

It defines email , birth , gender as properties of form, and it also has fields in Class Meta . I want to clearly understand their difference. Thanks in advance.

The Meta.fields property is for model forms . It is used to specify which model fields you want the model form to handle. So if you had a model like so:

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    date = models.DateField(auto_now=True)

You could define a form that only handles the name , because the date is auto-populated and you might not want the user to be able to set it manually:

class MyModelForm(forms.ModelForm):

    class Meta:
        model = Article
        fields = ['name']

This property is not used on regular (non-model) forms.

The form in your question subclasses UserCreationForm which is a ModelForm for the User model. So the fields property is specifying which of the User model properties you want the form to expose.

The field definitions on the class itself ( email , birth , gender ) are only necessary if:

  1. You want to add fields to the form that are not in the model. In this case, it looks like gender and birth are exactly such fields (unless you have a custom user model which has these fields).

  2. You want to customise the widget used to render a field. In this case you can override the original field and specify a custom widget. This is what is being done in the birth field where the widget has a restricted date range that would not exist in the default widget.

All the other fields ( username , email ) will be rendered using the default widgets because you haven't explicitly specified them in the class. password1 and password2 are not User model properties but are additional fields defined in the UserCreationForm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM