Django学习系列之ModelForm

前面两篇写了有关Form与Form的验证,今天我们来写些ModelForm,因为现在的web开发都基与db驱动的,所以models.py的定义是少不掉的,但我们会发现它的定义与forms.py定义很接近,为此减少输入,我们可以使用modelForm这个模块,可减少代码输入。


先定义models.py

#coding:utf-8
from django.db import models

SEX_CHOICES=(
('male','男'),
('female','女')
)

class Register(models.Model):
    sn = models.CharField(max_length=30,blank=True)
    nickname = models.CharField(max_length=50)
    username = models.CharField(max_length=50)
    password = models.CharField(max_length=50)
    sex = models.CharField(max_length=10,choices=SEX_CHOICES,null=True,blank=True)
    email = models.EmailField(max_length=50)
    phone = models.CharField(max_length=30,null=True,blank=True)
    birthday = models.DateField(max_length=50,null=True,blank=True)

    def __unicode__(self):
        return self.nickname


    class Meta:
        ordering = ('-sn',)    #排序

    
    #def clean(self):    #此部分本来是用来验证的,但想想还是将验证放到forms.py中吧。
    #    print self.nickname

再定义forms.py

#coding:utf-8
from django import forms
from mysite.models import Register
from django.core.exceptions import ValidationError
from django.forms.extras.widgets import SelectDateWidget

SEX_CHOICES=(
('male','男'),
('female','女')
)

BIRTH_YEAR_CHOICES = ('1980', '1981', '1982','1983','1984')

def validate_phone(value):
    if not value.isdigit():
        raise ValidationError(u'%s不是电话号码' % value)
    

class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'id':'pass'}))
    sex = forms.ChoiceField(widget=forms.RadioSelect,choices=SEX_CHOICES)
    birthday = forms.DateField(required=False,widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    phone = forms.CharField(required=False,validators=[validate_phone])

    class Meta:
        model = Register
        #fields = ['nickname','username','password','phone']
        fields = '__all__'

    def clean(self):
        cleaned_data=super(RegisterForm,self).clean()  
        nick_name=cleaned_data.get('nickname')  
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        email = cleaned_data.get('email')        

        if not nick_name:
            self._errors['nickname'] = self.error_class([u"请输入别名!"])

        if not username:
            self._errors['username'] = self.error_class([u"请输入用户名!"])
 
        if not password:
            self._errors['password'] = self.error_class([u"请输入密码!"])

        if nick_name == username and nick_name:
            self._errors['nickname'] = self.error_class([u"别名与用户名不能一样!"])

        if not email:
            self._errors['email'] = self.error_class([u"请输入正确邮箱!"])

        if email == "[email protected]":   #此部分可以扩展,将其数据从用户注册表中取出
            self._errors['email'] = self.error_class([u"邮箱已经存在,请换一个!"])
        return cleaned_data

以上仅供参考!

你可能感兴趣的:(python,django,ModelForm)