Python-django-from表单组件
from django.forms import Form from django.forms import fields from django.forms import widgets from django.forms.models import ModelChoiceField from django.core.validators import RegexValidator from django.core.validators import ValidationError from web01.models import Book, Publish class UserForm(Form): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['book'].widget.choices = Book.objects.values_list('id', 'name') name = fields.CharField( max_length=32, strip=True, required=True, error_message={'max_length': 'name最大长度为32'}, widget=widgets.TextInput(), label='姓名', label_suffix=':', ) book = fields.CharField( label='书名', widget=widgets.Select() ) author = ModelChoiceField( queryset=Book.objects.all(), # 返回的是 model对象的 __str__值 to_field_name='author', # 下拉选的 value值 empty_label='--请选择---', required=True, widget=widgets.Select(), label='作者' ) """ 双重验证 """ email = fields.ComboField( fields=[ fields.CharField(max_length=32, ), # 验证长度 fields.EmailField() # 验证格式 ], required=True, error_message={'max_length': 'Email最大长度为32', 'invalid': 'Email格式不正确!'}, ) """ 自带正则表达式验证 """ phone = fields.CharField( widget=widgets.Select(), validators=[RegexValidator(r'^[1-9]+$', '请输入数字', code='invalid1'), RegexValidator(r'^158[1-9]+$', '必须以159开头', code='invalid2')], label='电话号码', label_suffix=':', error_messages={'invalid1': '请输入数字', 'invalid2': '必须以159开头'} ) """ 对 name 进行二次判断 """ def clean_name(self): val = self.cleaned_data['name'] if val == '射雕英雄传': raise ValidationError('%s已经存在!' % val) return val """ 整体验证 """ def clean(self): data = self.cleaned_data name = data['name'] author = data['author'] if name == '射雕英雄传' and author == 'jack': raise ValidationError(' name不能是射雕英雄传 author不能是jack!') return data