前面兩篇寫了有關Form與Form的驗證,今天咱們來寫些ModelForm,由於如今的web開發都基與db驅動的,因此models.py的定義是少不掉的,但咱們會發現它的定義與forms.py定義很接近,爲此減小輸入,咱們能夠使用modelForm這個模塊,可減小代碼輸入。git
先定義models.pyweb
#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.nicknamedjango
class Meta:
ordering = ('-sn',) #排序
#def clean(self): #此部分原本是用來驗證的,但想一想仍是將驗證放到forms.py中吧。
# print self.nicknameide
再定義forms.pyui
#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 == "badboy@163.com": #此部分能夠擴展,將其數據從用戶註冊表中取出
self._errors['email'] = self.error_class([u"郵箱已經存在,請換一個!"])
return cleaned_data
spa
以上僅供參考!code
若是想了解更多,請關注咱們的公衆號
公衆號ID:opdevos
掃碼關注orm