django:模型和字段在元类中做什么?

sat*_*gie 1 python django django-forms

我正在关注 trydjango: coding for enterpreneurs 的 django 教程系列,并且对 django 形式的“模型”和“字段”的作用感到困惑。

模型.py

    from django.db import models
    # Create your models here.
    class SignUp(models.Model):
        email=models.EmailField()
        full_name=models.CharField(max_length=55, blank=True, null=True)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
        updated=models.DateTimeField(auto_now_add=False, auto_now=True)

        def __unicode__(self):
            return self.email
Run Code Online (Sandbox Code Playgroud)

表格.py

    from django import forms
    from .models import SignUp

    class SignUpForm(forms.ModelForm):
        class Meta:
            model=SignUp   # ?
            fields=['full_name','email']  # ?

        def clean_email(self):
            email=self.cleaned_data.get('email')
            email_base,provider=email.split("@")
            domain,extension=provider.split(".")
            if not domain == 'USC':
                raise forms.ValidationError("Please make sure you use your USC email")
            if not extension == "edu":
                raise forms.ValidationError("Please use valide edu address")
            return email

        def clean_full_name(self):
            full_name = self.cleaned_data.get('full_name')
            #write validation code
            return full_name
Run Code Online (Sandbox Code Playgroud)

小智 5

您正在使用一个特殊的 Form 类,它允许您从指定的 Model 类自动神奇地创建一个新的 Form。

模型字段显示您的表单将从哪个模型创建,字段字段显示模型类中的哪些字段要显示在您的新表单中。

链接到文档:https : //docs.djangoproject.com/en/1.9/topics/forms/modelforms/