You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

78 lines
3.9 KiB

from django import forms
from django.core.exceptions import ValidationError
from .models import *
import re
def age_validate(age):
if age <= 0 or age > 150:
raise ValidationError('年龄错误')
def mobile_validate(mobile):
mobile_re = re.compile(r'^1[3-9][0-9]{9}$')
if not mobile_re.match(mobile):
raise ValidationError('手机号格式错误')
STATUS = ((None, '请选择'), (0, '正常'), (1, '无效'))
# 用户信息表单
class UserInfoForm(forms.Form):
username = forms.CharField(label="用户名", min_length=2, widget=forms.widgets.TextInput(
attrs={'class': 'form-control', 'placeholder': '请输入用户名'}),
error_messages={'required': '用户姓名不能为空', 'min_length': '长度最小6位',
'invalid': '请输入正确用户名'})
password = forms.CharField(label='密码', min_length=6, max_length=10,
widget=forms.widgets.PasswordInput(attrs={'class': 'password'}, render_value=True),
help_text='密码长度为6-10个字符', error_messages={'required': '密码不能为空'})
age = forms.IntegerField(label='年龄', initial=1, min_value=1, max_value=150, validators=[age_validate],
error_messages={'required': '年龄不能为空'})
mobile = forms.CharField(label='手机号码', validators=[mobile_validate],
error_messages={'required': '手机号不能为空'})
status = forms.ChoiceField(label='状态', choices=STATUS, widget=forms.widgets.Select,
error_messages={'required': '状态不能为空'})
# status = forms.ModelChoiceField(label='状态', queryset=UserStatus.objects.all(), empty_label='请选择',
# error_messages={'required': '状态不能为空'})
createdate = forms.DateField(label='创建日期', required=False, input_formats=["%Y-%m-%d"])
class ImgFileForm(forms.Form):
name = forms.CharField()
heading = forms.FileField()
class UserInfoModelForm(forms.ModelForm):
confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(render_value=True),
error_messages={'required': '密码不能为空'})
class Meta:
model = UserBaseInfo
fields = ['username', 'password', 'confirm_password', 'age', 'mobile', 'status']
# fields = '__all__' 使用全部字段
labels = {'age': '年龄', 'mobile': '手机号码'}
widgets = {'password': forms.widgets.PasswordInput(attrs={'class': 'password'}, render_value=True),
'status': forms.widgets.Select(choices=STATUS, attrs={'selected': 0})}
error_messages = {'username': {'required': '用户名不能为空',
'min_length': '用户名至少两个字符',
'invalid': '输入正确的用户名'},
'password': {'max_length': '密码最长10位',
'min_length': '密码最少6位',
'required': '密码不能为空'},
'age': {'required': '年龄不能为空'},
'mobile': {'required': '手机号不能为空'},
'status': {'required': '用户状态不能为空'}}
def clean_mobile(self):
mobile = self.cleaned_data.get('mobile')
mobile_re = re.compile(r'^1[3-9][0-9]{9}$')
if not mobile_re.match(mobile):
raise ValidationError('手机号格式错误')
return mobile
def clean(self):
password = self.cleaned_data.get('password')
confirm_password = self.cleaned_data.get('confirm_password')
if password != confirm_password:
raise ValidationError('两次输入的密码不一致')