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

时间:2016-04-15 03:19:16

标签: python django django-forms

我遵循trydjango的django教程系列:为企业家编码,并且与django形式的“模型”和“字段”做了什么混淆。

models.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

forms.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

1 个答案:

答案 0 :(得分:3)

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

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

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