Django学习系列之ModelForm
2015-05-24 09:08
330 查看
前面两篇写了有关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 == "badboy@163.com": #此部分可以扩展,将其数据从用户注册表中取出
self._errors['email'] = self.error_class([u"邮箱已经存在,请换一个!"])
return cleaned_data
以上仅供参考!
先定义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 == "badboy@163.com": #此部分可以扩展,将其数据从用户注册表中取出
self._errors['email'] = self.error_class([u"邮箱已经存在,请换一个!"])
return cleaned_data
以上仅供参考!
相关文章推荐
- Django学习系列之Form验证
- Django学习系列之Form基础
- Django学习系列之Form验证
- Django学习笔记3 用ModelForm创建基于表单的页面
- Django学习系列之Form表单结合ajax
- Angular 学习系列 - - form.FormController、ngModel.NgModelController
- django学习——ModelForm操作
- Python自动化开发学习24-Django上(ModelForm)
- 学习Model-Glue框架的系列教程-Building your first Model-Glue Application中文理解通俗版(4)
- django学习08---Form表单提交
- django学习之三:model模型创建
- Django(八)下:Model操作和Form操作、序列化操作
- django学习之Model(二)
- 基于 Django1.10 文档的深入学习(16)——Authentication backends 之 class ModelBackend
- Django系列学习之二
- Django系列学习之十
- Caffe学习系列:caffemodel可视化
- django(7)modelform操作及验证、ajax操作普通表单数据提交、文件上传、富文本框基本使用
- Django models Form model_form 关系及区别
- Django学习笔记3:Model,Template,View 基本概念