class RegisterForm(Form): """ 注册页面的Form验证 """ username = fields.CharField( max_length=32, min_length=4, required=True, error_messages={ 'max_length': '用户名太长!', 'min_length': '用户名太短!', 'required': '用户名不能为空!', }, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'user', 'name': 'username' })) nickname = fields.CharField( max_length=32, min_length=4, required=True, error_messages={ 'max_length': '昵称太长!', 'min_length': '昵称太短!', 'required': '昵称不能为空!', }, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'nickname', 'name': 'nickname' })) email = fields.EmailField( required=True, error_messages={ 'required': '用户名不能为空!', }, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'email', 'name': 'email' })) password = fields.CharField( max_length=64, min_length=6, required=True, error_messages={ 'max_length': '密码太长!', 'min_length': '密码太短!', 'required': '密码不能为空!' }, widget=widgets.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Password', 'name': 'password' })) password02 = fields.CharField( max_length=64, min_length=6, required=True, error_messages={ 'max_length': '密码太长!', 'min_length': '密码太短!', 'required': '密码不能为空!' }, widget=widgets.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': '请再次确认', 'name': 'password02' })) code = fields.CharField( required=True, min_length=5, max_length=5, error_messages={ 'required': '验证码不能为空!', 'min_length': '验证码为5位!', 'max_length': '验证码为5位!', }, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'code', 'name': 'code' }))
class ExampleForm(Form): text = fields.CharField(max_length=10)
class AddressForm(DialogModelForm): # field to be superseeded by a select widget active_priority = fields.CharField( required=False, widget=widgets.HiddenInput(), ) use_primary_address = fields.BooleanField( required=False, initial=True, widget=CheckboxInput("use primary address"), ) # JS function to filter form_entities after removing an entity js_filter = "var list = [].slice.call(arguments); return list.filter(function(a) {{ return a.value != '{}'; }});" plugin_fields = ['plugin_id', 'plugin_order', 'use_primary_address'] class Meta: exclude = ('customer', 'priority',) def __init__(self, initial=None, instance=None, *args, **kwargs): self.multi_addr = kwargs.pop('multi_addr', False) self.allow_use_primary = kwargs.pop('allow_use_primary', False) self.form_entities = kwargs.pop('form_entities', []) if instance: cart = kwargs['cart'] initial = dict(initial or {}, active_priority=instance.priority) if instance.address_type == 'shipping': initial['use_primary_address'] = cart.shipping_address is None else: # address_type == billing initial['use_primary_address'] = cart.billing_address is None super(AddressForm, self).__init__(initial=initial, instance=instance, *args, **kwargs) @classmethod def get_model(cls): return cls.Meta.model @cached_property def field_css_classes(self): css_classes = {'*': getattr(Bootstrap3ModelForm, 'field_css_classes')} for name, field in self.fields.items(): if not field.widget.is_hidden: css_classes[name] = ['has-feedback', 'form-group', 'shop-address-{}'.format(name)] return css_classes @classmethod def form_factory(cls, request, data, cart): """ From the given request, update the database model. If the form data is invalid, return an error dictionary to update the response. """ # search for the associated address DB instance or create a new one current_address = cls.get_address(cart) try: active_priority = int(data.get('active_priority')) except (ValueError, TypeError): if data.get('use_primary_address'): active_priority = 'nop' else: active_priority = data.get('active_priority', 'new') active_address = cls.get_model().objects.get_fallback(customer=request.customer) else: filter_args = dict(customer=request.customer, priority=active_priority) active_address = cls.get_model().objects.filter(**filter_args).first() if data.pop('remove_entity', False): if active_address and (isinstance(active_priority, int) or data.get('is_pending')): active_address.delete() old_address = cls.get_model().objects.get_fallback(customer=request.customer) if old_address: faked_data = dict(data) faked_data.update(dict((field.name, old_address.serializable_value(field.name)) for field in old_address._meta.fields)) address_form = cls(data=faked_data) remove_entity_filter = cls.js_filter.format(active_priority) address_form.data.update( active_priority=str(old_address.priority), remove_entity_filter=mark_safe(remove_entity_filter), ) else: address_form = cls() address_form.data.update(active_priority='add', plugin_id=data.get('plugin_id'), plugin_order=data.get('plugin_order'), ) address_form.set_address(cart, old_address) elif active_priority == 'add': # Add a newly filled address for the given customer address_form = cls(data=data, cart=cart) if address_form.is_valid(): # prevent adding the same address twice all_field_names = [f.name for f in cls.get_model()._meta.get_fields()] filter_args = dict((attr, val) for attr, val in address_form.data.items() if attr in all_field_names and val) filter_args.update(customer=request.customer) if not cls.get_model().objects.filter(**filter_args).exists(): next_address = address_form.save(commit=False) if next_address: next_address.customer = request.customer next_address.priority = cls.get_model().objects.get_max_priority(request.customer) + 1 next_address.save() address_form.data.update(active_priority=str(next_address.priority)) else: address_form.data.update(active_priority='nop') address_form.set_address(cart, next_address) elif active_priority == 'new' or active_address is None and not data.get('use_primary_address'): # customer selected 'Add another address', hence create a new empty form initial = dict((key, val) for key, val in data.items() if key in cls.plugin_fields) address_form = cls(initial=initial) address_form.data.update(address_form.get_initial_data()) address_form.data.update(active_priority='add') elif current_address == active_address: # an existing entity of AddressModel was edited address_form = cls(data=data, instance=active_address, cart=cart) if address_form.is_valid(): next_address = address_form.save() address_form.set_address(cart, next_address) else: # an address with another priority was selected initial = dict(data) for attr in cls().get_initial_data().keys(): if hasattr(active_address, attr): initial.update({attr: getattr(active_address, attr)}) initial.update(active_priority=str(active_address.priority)) address_form = cls(data=initial, instance=current_address, cart=cart) address_form.set_address(cart, active_address) return address_form def get_response_data(self): return self.data def full_clean(self): super(AddressForm, self).full_clean() if self.is_bound and self['use_primary_address'].value(): # reset errors, since then the form is always regarded as valid self._errors = ErrorDict() def save(self, commit=True): if not self['use_primary_address'].value(): return super(AddressForm, self).save(commit) def as_div(self): # Intentionally rendered without field `use_primary_address`, this must be added # on top of the form template manually self.fields.pop('use_primary_address', None) return super(AddressForm, self).as_div() def as_text(self): bound_field = self['use_primary_address'] if bound_field.value(): return bound_field.field.widget.choice_label return super(AddressForm, self).as_text()
class usernameForm(forms.Form): username = fields.CharField(max_length=100)
class AddressForm(DialogModelForm): # field to be superseeded by a select widget active_priority = fields.CharField(required=False, widget=widgets.HiddenInput()) # JS function to filter form_entities after removing an entity js_filter = 'var list = [].slice.call(arguments); return list.filter(function(a) {{ return a.value != {}; }});' plugin_fields = ( 'plugin_id', 'plugin_order', ) class Meta: exclude = ( 'customer', 'priority', ) def __init__(self, initial=None, instance=None, *args, **kwargs): self.multi_addr = kwargs.pop('multi_addr', False) self.form_entities = kwargs.pop('form_entities', []) if instance: initial = initial or {} initial['active_priority'] = instance.priority super(AddressForm, self).__init__(initial=initial, instance=instance, *args, **kwargs) @classmethod def get_model(cls): return cls.Meta.model @property def field_css_classes(self): css_classes = {'*': getattr(Bootstrap3ModelForm, 'field_css_classes')} for name, field in self.fields.items(): if not field.widget.is_hidden: css_classes[name] = [ 'has-feedback', 'form-group', 'shop-address-{}'.format(name) ] return css_classes @classmethod def form_factory(cls, request, data, cart): """ From the given request, update the database model. If the form data is invalid, return an error dictionary to update the response. """ # search for the associated address DB instance or create a new one current_address, active_address = cls.get_address(cart), None try: active_priority = int(data.get('active_priority')) filter_args = dict(customer=request.customer, priority=active_priority) active_address = cls.get_model().objects.filter( **filter_args).first() except ValueError: active_priority = data.get('active_priority') except TypeError: active_priority = cls.default_priority if not active_address: active_address = cls.get_model().objects.get_fallback( customer=request.customer) if data.pop('remove_entity', False): if isinstance(active_priority, int): active_address.delete() old_address = cls.get_model().objects.get_fallback( customer=request.customer) faked_data = dict((key, getattr(old_address, key, val)) for key, val in data.items()) if old_address: faked_data.update(active_priority=old_address.priority) address_form = cls(data=faked_data, instance=old_address) if isinstance(active_priority, int): remove_entity_filter = cls.js_filter.format(active_priority) address_form.data.update( remove_entity_filter=mark_safe(remove_entity_filter)) address_form.set_address(cart, old_address) elif active_priority == 'add': # Add a newly filled address for the given customer address_form = cls(data=data, cart=cart) if address_form.is_valid(): # prevent adding the same address twice all_field_names = cls.get_model()._meta.get_all_field_names() filter_args = dict((attr, val) for attr, val in address_form.data.items() if attr in all_field_names and val) filter_args.update(customer=request.customer) if not cls.get_model().objects.filter(**filter_args).exists(): next_address = address_form.save(commit=False) if next_address: next_address.customer = request.customer next_address.priority = cls.get_model( ).objects.get_max_priority(request.customer) + 1 next_address.save() address_form.data.update( active_priority=next_address.priority) else: address_form.data.update(active_priority='nop') address_form.set_address(cart, next_address) elif active_address is None or active_priority == 'new': # customer selected 'Add another address', hence create a new empty form initial = dict((key, val) for key, val in data.items() if key in cls.plugin_fields) address_form = cls(initial=initial) address_form.data.update(address_form.get_initial_data()) address_form.data.update(active_priority='add') address_form.set_address(cart, None) elif current_address == active_address: # an existing entity of AddressModel was edited address_form = cls(data=data, instance=active_address) if address_form.is_valid(): next_address = address_form.save() address_form.set_address(cart, next_address) else: # an address with another priority was selected initial = dict(data) for attr in cls().get_initial_data().keys(): if hasattr(active_address, attr): initial.update({attr: getattr(active_address, attr)}) initial.update(active_priority=active_address.priority) address_form = cls(data=initial, instance=current_address) address_form.set_address(cart, active_address) return address_form def get_response_data(self): return self.data
class FormsAddUser(forms.Form): username = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'username', 'placeholder': '用户名' }), max_length=18, min_length=3, required=True, error_messages={ 'required': '用户名不能为空', 'max_length': '用户名太长了,不能超过18个字符', 'min_length': '用户名太短了,最少5个字符', 'invalid': '输入的参数不合法' }) password = fields.CharField( widget=widgets.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password', 'placeholder': '密码' }), max_length=20, min_length=8, required=True, error_messages={ 'required': '密码不能为空', 'max_length': '用户名太长了,不能超过20位字符', 'min_length': '用户名太短了,至少8位字符', 'invalid': '输入的参数不合法' }) role_id = fields.IntegerField(widget=widgets.Select(attrs={ 'class': 'form-control', 'name': 'role_id' })) # 动态获取数据库数据 def __init__(self, *args, **kwargs): super(FormsAddUser, self).__init__(*args, **kwargs) self.fields[ 'role_id'].widget.choices = models.Role.objects.values_list( 'id', 'caption') sex = fields.ChoiceField(choices=( (1, '男'), (0, '女'), ), initial=1, widget=widgets.RadioSelect(attrs={ 'name': 'sex', 'class': 'radio-inline' })) realname = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'realname', 'placeholder': '真实姓名' }), max_length=20, min_length=2, required=True, error_messages={ 'required': '不能为空', 'max_length': '用户名太长了,不能超过20个字符', 'min_length': '用户名太短了,至少2个字符', 'invalid': '输入的参数不合法' }) phone = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'phone', 'placeholder': '手机号' }), max_length=11, min_length=11, required=True, error_messages={ 'required': '不能为空', 'max_length': '手机号格式不对', 'min_length': '手机号格式不对', 'invalid': '输入的参数不合法' }) email = fields.CharField( widget=widgets.EmailInput(attrs={ 'class': 'form-control', 'name': 'email', 'placeholder': '邮箱' }), max_length=30, min_length=3, required=True, error_messages={ 'required': '不能为空', 'max_length': '邮箱名太长了,不能超过30个字符', 'min_length': '邮箱名太短了,至少3个字符', 'invalid': '输入的参数不合法' }) def clean_username(self): v = self.cleaned_data['username'] if models.User.objects.filter(username=v).count(): raise ValidationError('用户名已存在') return v # clean方法,对整体错误进行验证 def clean(self): value_dict = self.cleaned_data v1 = value_dict.get('username') if v1 == "lee": raise ValidationError('整体错误信息') return self.cleaned_data
class WidghtForm(DForms.Form): w1 = fields.CharField(widget=widgets.ClearableFileInput)
class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices)
class CommentForms(forms.Form): comment_content = fields.CharField()
class RegisterForm(forms.Form): username = fields.CharField( max_length=16, min_length=1, required=True, strip=True, validators=[ RegexValidator(r'^[a-zA-Z\u4e00-\u9fa5]+$', '用户名不能有特殊字符或数字'), ], widget=widgets.TextInput(attrs={"placeholder": "用户名"})) email = fields.CharField( required=True, strip=True, validators=[ RegexValidator(r'^\d{5,12}@[qQ][qQ]\.(com|cn)$', '只能是QQ邮箱'), ], widget=widgets.TextInput(attrs={"placeholder": "邮箱"})) pwd = fields.CharField( required=True, max_length=32, min_length=6, strip=True, widget=widgets.PasswordInput(attrs={"placeholder": "密码"}), validators=[ RegexValidator(r"([0-9]+.+[a-zA-Z]+|[a-zA-Z]+.+[0-9]+)", "密码必须包含数字跟字母"), ]) re_password = fields.CharField( required=True, max_length=32, min_length=6, strip=True, widget=widgets.PasswordInput(attrs={"placeholder": "确认密码"})) confirm_code = fields.CharField( required=True, max_length=4, min_length=4, strip=True, widget=widgets.TextInput(attrs={ "placeholder": "验证码", "style": "width: 50%; float: left;" })) def __init__(self, right_code="", *args, **kwargs): super().__init__(*args, **kwargs) self.right_code = right_code def clean_confirm_code(self): # 判断验证码是否输入正确 code = self.cleaned_data['confirm_code'] if not self.right_code == code: raise ValidationError("验证码有误") return code def clean_username(self): # 判断用户名是否有重复 username = self.cleaned_data["username"] if models.User.objects.filter(username=username).exists(): # 如果存在抛出异常 raise ValidationError("该用户名已存在") return username def clean_email(self): # 判断邮箱是否重复 email = self.cleaned_data['email'] if models.User.objects.filter(email=email).exists(): raise ValidationError("该邮箱已注册") return email def clean(self): try: # 在这里面判断两次输入的密码是否一致 password = self.cleaned_data['pwd'] re_password = self.cleaned_data['re_password'] if not password == re_password: # 两次输入的密码不一致 raise ValidationError("两次密码输入不一致") return self.cleaned_data except KeyError: return self.cleaned_data
class LoginForm(forms.Form): username =fields.CharField(validators=[RegexValidator(r'^[a-zA-Z0-9_-]{4,16}$'),],\ error_messages={'required':'用户名不能为空','min_length':'用户名最小4位','max_length':'最大长度16位'}) password = fields.CharField(error_messages={'invalid': '密码不正确'})
class AddAssetForm(Form): """新增资产Form表单""" device_type_id = fields.ChoiceField( choices=models.Asset.device_type_choices, widget=widgets.Select(attrs={})) device_status_id = fields.ChoiceField( choices=models.Asset.device_status_choices, widget=widgets.Select) hostname = fields.CharField( error_messages={ "required": "主机名不能为空", }, widget=widgets.Input(attrs={ "class": "form-control", "name": "hostname", "type": "text" })) cabinet_num = fields.CharField(required=False, widget=widgets.Input( attrs={ "class": "form-control", "placeholder": "请输入机柜号,没有可为空", "name": "hostname", "type": "text" })) cabinet_order = fields.CharField(required=False, widget=widgets.Input( attrs={ "class": "form-control", "placeholder": "请输入机柜中所在位置,没有可为空", "name": "hostname", "type": "text" })) idc_id = fields.ChoiceField(error_messages={ "required": "机房不能为空", }, choices=[], widget=widgets.Select) business_unit_id = fields.ChoiceField(required=False, choices=[], widget=widgets.Select) tag = MultipleChoiceField(required=False, choices=models.Tag.objects.all().values_list( 'id', 'name'), widget=widgets.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(AddAssetForm, self).__init__(*args, **kwargs) values = models.IDC.objects.all().values_list('id', 'name', 'floor') idc_values = [['', '---------']] for i in values: idc_values.append([i[0], "%s-%s" % (i[1], i[2])]) self.fields['idc_id'].choices = idc_values values = models.BusinessUnit.objects.values_list('id', 'name') business_unit_values = [['', '---------']] for i in values: business_unit_values.append([i[0], i[1]]) self.fields['business_unit_id'].choices = business_unit_values
class UserForm(dforms.Form): username = fields.CharField() email = fields.EmailField()
class RegForm(Form): email = fields.EmailField( required=True, error_messages={'required':'邮箱不能为空!'}, widget=widgets.EmailInput( attrs={'placeholder': 'Email💃💃💃', 'type': "email", 'class': "form-control"}) ) username = fields.CharField( required=True, min_length=3, max_length=16, error_messages={ 'required' : '用户名不能为空!', 'min_length' : '稍微长点哦', 'max_length' : '稍微短点哦' }, widget=widgets.TextInput(attrs={'placeholder':'输!名字!','type':"text",'class':"form-control"}) ) password = fields.CharField( required=True, min_length=6, max_length=16, error_messages={ 'required' : '密码不能为空', 'min_length' : '密码短短短', 'max_length' : '稍微短点兄弟', 'invalid' : '密码格式有问题' }, widget=widgets.PasswordInput(attrs={'placeholder': '输!密码!', 'type': "password", 'class': "form-control"}), validators=[RegexValidator('/d+','密码只能为数字.')] # validators=[RegexValidator('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{8,16}$', # '可以包含数字、字母、下划线,并且要同时含有数字和字母,且长度要在8-16位之间。')] ) repassword = fields.CharField( required=True, min_length=6, max_length=16, error_messages={ 'required': '密码不能为空', }, widget=widgets.PasswordInput( attrs={'placeholder': '重复密码', 'type': "password", 'class': "form-control"}) ) tel = fields.CharField( required=True, max_length=15, min_length=11, error_messages={ 'required' : '电话号码不能为空!', 'min_length' : '你家电话号码这么短?', 'max_length' : '你家走哪买的电话卡' }, widget=widgets.NumberInput( attrs={'placeholder': 'shu! dianhua !', 'type': "number", 'class': "form-control"}) ) nickname = fields.CharField( required=True, max_length=32, min_length=1, error_messages={ 'required' : '昵称不阔以为空!', 'min_length' : '您太短', 'max_length' : '昵称长度超过最大限制' }, widget=widgets.TextInput( attrs={'placeholder': "shu! nicheng!", 'type': "text", 'class': "form-control"}) ) #头像不需要验证,所以不用写在form里面.可以拿出来单独写 # avatar = fields.FileField( # required=False, # widget=widgets.FileInput(attrs={'id':'avatar'}) # ) #下面是格式输入通过, 然后可以拿到用户输入的数据,去和数据库的值比对,用到的是源码中的clean_字段名的方法 def clean_username(self): # 因为格式没错,所以我们可以从clean_data中,拿到用户输入的数据 user = self.cleaned_data.get('username') # 去比对,看用户输入的用户名在数据库里是否存在 is_exist = models.User.objects.filter(username=user).count() if is_exist: # 如果存在,就捕捉错误.用raise V方法 raise ValidationError('用户名已存在,请重新输入') return user def clean_email(self): try : email = self.cleaned_data.get('email') is_exist = models.Userinfo.objects.filter(email=email).count() if is_exist: raise ValidationError('邮箱已被注册!') return email except Exception as e: print('except: ' + str(e)) raise ValidationError(u"注册账号需为邮箱格式") #form本来就是用来验证,所以有关验证的我们尽量都放在form组件里面来做. def clean(self): if self.cleaned_data.get('password')==self.cleaned_data.get('repassword'): return self.cleaned_data else: raise ValidationError('两次密码输入不一致!')
class stu_form(forms.Form): # stuno = fields.IntegerField(required=True, # error_messages={ # 'required':'请填写学号', # # },) stuname = fields.CharField( max_length=64, required=True, error_messages={ 'required': '请填写学员姓名', 'max_length': '学员姓名不可超过32个字' }, ) phone = fields.CharField( max_length=20, min_length=11, required=True, validators=[ phone_validate, ], error_messages={ 'required': '请填写手机号码', 'max_length': '手机号最长不可超过20位', 'min_length': '手机号至少11位' }, ) qq = fields.CharField( max_length=15, validators=[ qqNo_validate, ], error_messages={ 'required': '请填写QQ号', }, ) """coursId = ModelChoiceField( required=True, queryset=models.Courses.objects.all(), empty_label="-------", error_messages={ 'required': '请选择科目!', }, )""" coursId = fields.IntegerField(widget=forms.Select( attrs={ 'class': 'select', 'id': 'coursID', 'onChange': 'getClasOption(this.value)' }, choices=COURSES_LIST, ), ) clsId = fields.IntegerField( required=False, widget=forms.Select(choices=(('', '-----'), ), ), ) # clsId = ModelChoiceField( # required=True, # #queryset=models.Clas.objects.all(), # queryset=models.Clas.objects.filter(couId=coursId), # empty_label="-------", # error_messages={ # 'required': '请选择班级!', # }, # ) clstype = fields.IntegerField(widget=forms.Select(choices=( (1, "现场"), (2, "网络"), ), )) tu_total = fields.FloatField(min_value=0.0, required=True, validators=[ digit_validate, ], error_messages={ 'min_value': '请输入正数', 'required': '请填写学费总额' }) tu_paid = fields.FloatField(min_value=0.0, required=True, validators=[ digit_validate, ], error_messages={ 'min_value': '请输入正数', 'required': '请填写已交学费' }) is_recom = fields.IntegerField(widget=forms.Select(choices=( (1, "是"), (2, "否"), ), )) #recom = fields.IntegerField(widget=forms.Select()) '''recom = ModelChoiceField( queryset=models.Stu.objects.all(), empty_label="-------" )''' recom = fields.CharField(required=False, max_length=64) def __init__(self, *args, **kwargs): super(stu_form, self).__init__(*args, **kwargs) #self.fields['clsId'].widget.choices = models.Clas.objects.all().values_list('id',"clsName") #self.fields['recom'].widget.choices = models.Stu.objects.all().values_list('id',"name") # def clean_stuno(self): # sno = self.cleaned_data['stuno'] # if sno: # st = models.Stu.objects.filter(Sno=sno) # if st: # raise ValidationError('输入学号已存在,请重新输入!') # else: # return sno def clean_coursId(self): coursId = self.cleaned_data['coursId'] print("coursID> ", coursId) c = models.Courses.objects.get(id=coursId) if not c: raise ValidationError('请选择所学科目!!!!') else: print("form course: ", c) return c def clean_clsId(self): clsId = self.cleaned_data['clsId'] cls = models.Clas.objects.filter(id=clsId).first() if not cls: raise ValidationError('请选择班级!!!!') else: print("form cls: ", type(cls)) return cls def clean_recom(self): is_recom = self.cleaned_data['is_recom'] rec = self.cleaned_data['recom'] s = models.Stu.objects.filter(name=rec).first() if is_recom == 1: if not rec: #print("未输入推荐人") raise ValidationError('请选择推荐人!') else: if not s: #print("-----打印错误-----") raise ValidationError('该学员不存在') else: print("form rec:", rec, type(rec)) print("from s:", s, type(s)) return s else: if rec: raise ValidationError('不需要填写推荐人') else: return s
class ReplyForms(forms.Form): reply_content = fields.CharField()
class clas_form(forms.Form): clsId = fields.IntegerField(widget=forms.HiddenInput(), initial=0) clsname = fields.CharField( max_length=64, required=True, error_messages={ 'required': '请填写班级名称', 'max_length': '班级名称不可超过32个字' }, ) coursId = ModelChoiceField( required=True, queryset=models.Courses.objects.all().order_by( '-id'), #新增班级页面,初始化科目下拉列表 empty_label="-------", #ModelChoiceField 具有empty_label属性 error_messages={ 'required': '请选择科目!', }, ) starttime = fields.DateTimeField( required=True, error_messages={ 'required': '请填写开课日期', 'invalid': '输入格式不正确,例:2017-01-01', }, ) endtime = fields.DateTimeField( required=True, error_messages={ 'required': '请填写结课日期', 'invalid': '输入格式不正确,例:2017-01-01', }, ) #op = fields.CharField(widget=forms.HiddenInput(),initial='add') # class Meta: # model = models.Clas # fields = '__all__' def clean_clsname(self): clsname = self.cleaned_data['clsname'] clsId = self.data['clsId'] #print("123:",clsname) #op = self.cleaned_data['op'] if clsId == 0: #clsId 为0,代表新增班级 if clsname: c = models.Clas.objects.filter(clsName=clsname) if c: raise ValueError('班级名称已存在,请重新输入!') else: return clsname else: #clsId 不为0,代表编辑班级 if clsname: c = models.Clas.objects.filter(clsName=clsname).exclude( id=clsId) #查询数据库中是否存在相同名称时,排除当前班级 if c: raise ValueError('班级名称已存在,请重新输入!') else: return clsname #clsId = self.cleaned_data['clsId'] #print("++++++++",clsId) def clean(self): clean_data = self.cleaned_data start = clean_data.get('starttime') end = clean_data.get('endtime') if start and end: if end <= start: raise ValidationError('结课日期必须大于开课日期') else: return self.cleaned_data
class UserForms(forms.Form): username = fields.CharField( error_messages={'required':'用户名不能为空'}, validators=[RegexValidator('^[\u4e00-\u9fa5_a-zA-Z0-9-]+$', '用户名只能包含中文,数字,字母,下划线,横杠')], )
class FormsAddAsset(forms.Form): hostname = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'hostname', 'placeholder': '主机名' }), max_length=25, min_length=3, required=True, error_messages={ 'required': '主机名不能为空', 'max_length': '主机名太长了,不能超过25个字符', 'min_length': '主机名太短了,最少5个字符', 'invalid': '输入的参数不合法' }) ip_address = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'ip_address', 'placeholder': 'IP地址' }), max_length=16, min_length=7, required=True, error_messages={ 'required': 'IP地址不能为空', 'max_length': 'IP地址太长了,不能超过16位', 'min_length': 'IP地址太短了,最少7位以上', 'invalid': '输入的参数不合法' }) port = fields.IntegerField(widget=widgets.TextInput( attrs={ 'class': 'form-control', 'name': 'port', 'placeholder': '端口', 'value': '22' }), max_value=65535, min_value=10, required=True, error_messages={ 'required': '端口不能为空', 'max_value': '端口太大了,不能超过65535', 'min_value': '端口太小了,最少为10以上', 'invalid': '输入的参数不合法' }) idc_id = fields.IntegerField(widget=widgets.Select(attrs={ 'class': 'form-control', 'name': 'idc_id' })) assets_type = fields.ChoiceField( choices=( (1, '虚拟机'), (2, '交换机'), (3, '服务器'), (4, '防火墙'), ), initial=1, widget=widgets.RadioSelect(attrs={ 'name': 'assets_type', 'class': 'radio-inline' })) project_name_id = fields.IntegerField(widget=widgets.Select( attrs={ 'class': 'form-control', 'name': 'project_name_id' })) env_type_id = fields.IntegerField(widget=widgets.Select( attrs={ 'class': 'form-control', 'name': 'env_type_id' })) cpu = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'cpu', 'placeholder': 'cpu' }), max_length=5, min_length=2, required=True, error_messages={ 'required': 'cpu不能为空', 'max_length': 'cpu太长了,不能超过5个字符', 'min_length': 'cpu太短了,最少2个字符', 'invalid': '输入的参数不合法' }) memory = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'memory', 'placeholder': '内存' }), max_length=6, min_length=2, required=True, error_messages={ 'required': '内存不能为空', 'max_length': '内存太长了,不能超过6个字符', 'min_length': '内存太短了,最少2个字符', 'invalid': '输入的参数不合法' }) disk = fields.CharField( widget=widgets.TextInput(attrs={ 'class': 'form-control', 'name': 'disk', 'placeholder': '硬盘' }), max_length=6, min_length=2, required=True, error_messages={ 'required': '硬盘不能为空', 'max_length': '硬盘太长了,不能超过6个字符', 'min_length': '硬盘太短了,最少2个字符', 'invalid': '硬盘的参数不合法' }) # def clean_hostname(self): # v = self.cleaned_data['hostname'] # if models.Host.objects.filter(hostname=v).count(): # raise ValidationError('主机名已存在') # return v def __init__(self, *args, **kwargs): super(FormsAddAsset, self).__init__(*args, **kwargs) self.fields['idc_id'].widget.choices = models.IDC.objects.values_list( 'id', 'name') self.fields[ 'project_name_id'].widget.choices = models.Projects.objects.values_list( 'id', 'project_name') self.fields[ 'env_type_id'].widget.choices = models.Envlists.objects.values_list( 'id', 'env')
class FM(forms.Form): ''' 这是用form 制作的验证 ''' email = fields.EmailField( error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }, widget=widgets.Input(attrs={ 'name': 'email', 'onblur': 'check_exist(this)' }), ) user_name = fields.CharField( error_messages={'required': '用户名不能为空.'}, widget=widgets.Input(attrs={ 'name': 'user_name', 'onblur': 'check_exist(this)' }), label="用户名", ) password = fields.CharField( max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, widget=widgets.PasswordInput(attrs={ 'name': 'password', 'class': 'password', 'onblur': 'confirmpass()' }), label="密码", ) password2 = fields.CharField( max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, widget=widgets.PasswordInput(attrs={ 'name': 'password2', 'class': 'password2', 'onblur': 'confirmpass()' }), label="确认密码", ) class Meta: model = Users fields = ("user_name", "password", "email") # 自定义方法(局部钩子),密码必须包含字母和数字 def clean_password(self): if self.cleaned_data.get('password').isdigit( ) or self.cleaned_data.get('password').isalpha(): raise forms.ValidationError('密码必须包含数字和字母') else: return self.cleaned_data['password'] # def clean_valid_code(self): # 检验验证码正确;之前生成的验证码保存在了了session中 # if self.cleaned_data.get ( 'valid_code' ).upper () == self.request.session.get ( 'valid_code' ): # return self.cleaned_data['valid_code'] # else: # raise forms.ValidationError ( '验证码不正确' ) # 自定义方法(全局钩子, 检验两个字段),检验两次密码一致; def clean(self): if self.cleaned_data.get('password') != self.cleaned_data.get( 'password2'): raise forms.ValidationError('密码不一致') else: return self.cleaned_data
class MyForm(Form): user = fields.CharField( validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], )
class TeacherForm(forms.Form): name = fields.CharField(max_length=32,required=True ,error_messages={'required':'教师名称不能为空'})
class RegisterForm(Form): '用户注册' username = fields.CharField(max_length=32, min_length=2, required=True, widget=widgets.TextInput(attrs={ 'class': "form-control", 'placeholder': "用户名" })) # nickname = fields.CharField(max_length=32, min_length=2, required=True, # widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': "昵称"})) email = fields.EmailField(max_length=32, min_length=2, required=True, widget=widgets.TextInput(attrs={ 'class': "form-control", 'placeholder': "邮箱" })) password = fields.CharField( max_length=32, min_length=2, required=True, widget=widgets.PasswordInput(attrs={ 'class': "form-control", 'placeholder': "密码" })) password2 = fields.CharField( max_length=32, min_length=2, required=True, widget=widgets.PasswordInput(attrs={ 'class': "form-control", 'placeholder': "请再次输入密码" })) check_code = fields.CharField(widget=widgets.TextInput( attrs={ 'class': "form-control", 'placeholder': "验证码" })) avatar = fields.ImageField(widget=widgets.FileInput( attrs={ 'class': 'user_avatar', 'style': "position: absolute;right: -460px;opacity:0" }), required=False) role = fields.ChoiceField( widget=widgets.Select(attrs={'class': "form-control"}), initial=1) department = fields.ChoiceField(widget=widgets.Select( attrs={'class': "form-control"})) # remember=fields.ChoiceField(widget=widgets.CheckboxInput) def __init__(self, request, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.request = request self.fields['role'].choices = models.Role.objects.all().values_list( 'rid', 'title') self.fields['department'].choices = models.Department.objects.all( ).values_list('did', 'title') def clean_username(self): username = self.cleaned_data.get('username') print(username, 'username----------') print(self.cleaned_data, '--------------clean_username') username_database = models.Identify_user.objects.filter( username=username).values('username').first() print(username_database, '从公司数据库获取的信息') if username_database: return username raise ValidationError('用户不在本公司') def clean_email(self): email = self.cleaned_data.get('email') print(email, 'email----------') print(self.cleaned_data, '--------------clean_email') email_database = models.Identify_user.objects.filter( email=email).values('email').first() print(email_database, '从公司数据库获取的信息') if email_database: return email raise ValidationError('用户邮箱不在本公司') def clean_check_code(self): input_code = self.cleaned_data.get('check_code') session_code = self.request.session.get('check_code') print('-----form ---') print(self.cleaned_data) print(input_code, session_code) if input_code.upper() == session_code: return input_code raise ValidationError('验证码错误') def clean(self): password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') # if password1==password2: # print('密码一致') # return self.cleaned_data # else: # self.add_error('password2',ValidationError('密码不一致')) print('进入密码确认') username_form = self.cleaned_data.get('username') email_form = self.cleaned_data.get('email') username_database_from_email = models.Identify_user.objects.filter( email=email_form).values('username').first( ) # 依据用户输入的Email查找数据库中的username再与用户输入的username比对 print('username_form', username_form, 'username_database_from_email', username_database_from_email) if username_database_from_email != None: if username_form == username_database_from_email.get('username'): print('用户名和Email比对正确') if password2 == password1: return self.cleaned_data else: self.add_error('username', ValidationError('密码不一致')) else: self.add_error('username', ValidationError('用户名和邮箱不符')) else: self.add_error('username', ValidationError('用户名或邮箱不在公司数据库'))
class ClassForm(forms.Form): title = fields.CharField(max_length=32,required=True ,error_messages={'required':'班级名称不能为空'})
class RegForm(Form): email = fields.EmailField( required=True, error_messages={ 'required': '请输入邮箱地址', 'invalid': '请输入正确的邮箱格式', }, widget=widgets.TextInput(attrs={ 'placeholder': '需要通过邮件激活账户', 'class': 'form-control' })) # widget=widgets.TextInput(attrs={'placeholder': '需要通过邮件激活账户'})), tel = fields.IntegerField( required=True, error_messages={ 'required': '请输入手机号码', }, widget=widgets.TextInput(attrs={ 'placeholder': '激活帐户需要手机短信验证', 'class': 'form-control' })) username = fields.CharField( required=True, max_length=18, min_length=4, error_messages={ 'required': '请输入登陆用户名', 'min_length': '不合要求,至少为4个字符', 'max_length': '不合要求,至多为18个字符', }, widget=widgets.TextInput(attrs={ 'placeholder': '登录用户名,不少于4个字符', 'class': 'form-control' })) nickname = fields.CharField( required=True, max_length=18, min_length=4, error_messages={ 'required': '请输入显示名称', 'min_length': '不合要求,至少为4个字符', 'max_length': '不合要求,至多为18个字符', }, widget=widgets.TextInput(attrs={ 'placeholder': '即昵称,不少于2个字符', 'class': 'form-control' })) avatar = fields.FileField(required=False) password = fields.CharField( required=True, min_length=8, max_length=30, error_messages={ 'required': '请输入密码', 'min_length': '不合要求,密码长度要求8~30位', 'max_length': '不合要求,密码长度要求8~30位' }, widget=widgets.TextInput(attrs={ 'placeholder': '至少8位,必须包含字母、数字', 'class': 'form-control' }), validators=[RegexValidator('\d+', '密码必须包含字母、数字的组合')]) repeat_password = fields.CharField( required=True, error_messages={'required': '请输入确认密码'}, widget=widgets.TextInput(attrs={ 'placeholder': '请输入确认密码', 'class': 'form-control' })) def clean_email(self): email = self.cleaned_data['email'] is_exsit = models.UserInfo.objects.filter(email=email) if is_exsit: raise ValidationError('邮箱已经存在!') else: return email def clean_username(self): user = self.cleaned_data['username'] is_exsit = models.UserInfo.objects.filter(username=user) if is_exsit: raise ValidationError('登陆用户名已被使用!') else: return user def clean_nickname(self): nickname = self.cleaned_data['nickname'] is_exsit = models.UserInfo.objects.filter(nickname=nickname) if is_exsit: raise ValidationError('显示名称已被使用!') else: return nickname def clean(self): password = self.cleaned_data.get('password') repeat_password = self.cleaned_data.get('repeat_password') if password != repeat_password: raise ValidationError('确认密码错误') else: return self.cleaned_data
class RegisterUserForm(NgModelFormMixin, NgFormValidationMixin, UniqueEmailValidationMixin, Bootstrap3ModelForm): form_name = 'register_user_form' scope_prefix = 'form_data' field_css_classes = 'input-group has-feedback' email = fields.EmailField(label=_("Your e-mail address")) preset_password = fields.BooleanField( label=_("Preset password"), widget=widgets.CheckboxInput(), required=False, help_text=_( "Send a randomly generated password to your e-mail address.")) password1 = fields.CharField( label=_("Choose a password"), widget=widgets.PasswordInput, min_length=6, help_text=_("Minimum length is 6 characters."), ) password2 = fields.CharField( label=_("Repeat password"), widget=widgets.PasswordInput, min_length=6, help_text=_("Confirm password."), ) class Meta: model = CustomerModel fields = ( 'email', 'password1', 'password2', ) def __init__(self, data=None, instance=None, *args, **kwargs): if data and data.get('preset_password', False): pwd_length = max(self.base_fields['password1'].min_length, 8) password = get_user_model().objects.make_random_password( pwd_length) data['password1'] = data['password2'] = password super(RegisterUserForm, self).__init__(data=data, instance=instance, *args, **kwargs) def clean(self): cleaned_data = super(RegisterUserForm, self).clean() # check for matching passwords if 'password1' not in self.errors and 'password2' not in self.errors: if cleaned_data['password1'] != cleaned_data['password2']: msg = _("Passwords do not match") raise ValidationError(msg) return cleaned_data def save(self, request=None, commit=True): self.instance.user.is_active = True self.instance.user.email = self.cleaned_data['email'] self.instance.user.set_password(self.cleaned_data['password1']) self.instance.recognize_as_registered(request, commit=False) customer = super(RegisterUserForm, self).save(commit) password = self.cleaned_data['password1'] if self.cleaned_data['preset_password']: self._send_password(request, customer.user, password) user = authenticate(username=customer.user.username, password=password) login(request, user) return customer def _send_password(self, request, user, password): current_site = get_current_site(request) context = Context({ 'site_name': current_site.name, 'absolute_base_uri': request.build_absolute_uri('/'), 'email': user.email, 'password': password, 'user': user, }) subject = select_template([ '{}/email/register-user-subject.txt'.format( app_settings.APP_LABEL), 'shop/email/register-user-subject.txt', ]).render(context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = select_template([ '{}/email/register-user-body.txt'.format(app_settings.APP_LABEL), 'shop/email/register-user-body.txt', ]).render(context) user.email_user(subject, body)
class TestForm(*classes): action_class = mock_action_class title = fields.CharField()
class HostForm(Form): """ host表单验证 """ def __init__(self, *args, **kwargs): super(HostForm, self).__init__(*args, **kwargs) self.fields['service_id'].choices = models.Services.objects.values_list('id', 'name') self.fields['idc_id'].choices = models.Idc.objects.values_list('id', 'idc') self.fields['status_id'].choices = models.Status.objects.values_list('id', 'status') self.fields['owner_id'].choices = models.User.objects.values_list('id', 'username') hostname = fields.CharField( required=True, label=u'主机名', max_length=32, error_messages={'required': '主机名不能为空!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'主机名'}) ) private_ip = fields.GenericIPAddressField( required=True, label=u'内网IP', max_length=32, # null=True, error_messages={'required': 'IP不合法!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'内网IP'}) ) public_ip = fields.GenericIPAddressField( required=True, label=u'公网IP', max_length=32, # null=True, error_messages={'required': 'IP不合法!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'公网IP'}) ) os = fields.CharField( required=True, label=u'OS', max_length=16, # default="ubuntu 16.04", error_messages={'required': 'os类型错误!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'os'}) ) cpu = fields.CharField( required=True, label=u'cpu', max_length=10, error_messages={'required': '格式错误!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'cpu'}) ) mem = fields.CharField( required=True, label=u'mem', max_length=16, error_messages={'required': '格式错误!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'mem'}) ) disk = fields.CharField( required=True, label=u'disk', max_length=16, error_messages={'required': '格式错误!'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': u'disk'}) ) service_id = fields.ChoiceField( required=True, label=u'业务线', choices=[], error_messages={'required': '业务线类型错误!'}, widget=widgets.Select(attrs={'class': 'form-control'}) ) idc_id = fields.ChoiceField( required=True, label=u'IDC', choices=[], error_messages={'required': 'IDC类型错误!'}, widget=widgets.Select(attrs={'class': 'form-control'}) ) status_id = fields.ChoiceField( required=True, label=u'主机状态', choices=[], error_messages={'required': '主机状态类型错误!'}, widget=widgets.Select(attrs={'class': 'form-control'}) ) owner_id = fields.ChoiceField( required=True, label=u'负责人', choices=[], error_messages={'required': '负责人未知错误!'}, widget=widgets.Select(attrs={'class': 'form-control'}) )
class BusinessUnitAddForm(forms.Form): """ 添加资产业务线视图表单验证类 """ name = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='业务线名称', help_text='必填项', widget=widgets.TextInput(attrs={'class': 'form-control'})) contact_id = fields.IntegerField(error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='联系人', help_text='必填项', widget=widgets.Select(choices=[], attrs={ 'class': 'form-control', 'placeholder': '联系人' })) manager_id = fields.IntegerField(error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='管理人', help_text='必填项', widget=widgets.Select(choices=[], attrs={ 'class': 'form-control', 'placeholder': '管理人' })) def __init__(self, *args, **kwargs): super(BusinessUnitAddForm, self).__init__(*args, **kwargs) self.fields[ 'contact_id'].widget.choices = models.UserProfile.objects.values_list( 'id', 'name') self.fields[ 'manager_id'].widget.choices = models.UserProfile.objects.values_list( 'id', 'name') def clean_name(self): name = self.cleaned_data.get('name') n = models.BusinessUnit.objects.filter( name=self.cleaned_data.get('name')).count() if not n: return self.cleaned_data.get('name') else: raise ValidationError(_('业务线%(name)s已存在'), code='invalid', params={'name': name}) def clean_contact_id(self): c = models.UserProfile.objects.filter( id=self.cleaned_data.get('contact_id')).count() if c: return self.cleaned_data.get('contact_id') else: raise ValidationError(_('联系人不存在'), code='invalid') def clean_manager_id(self): m = models.UserProfile.objects.filter( id=self.cleaned_data.get('manager_id')).count() if m: return self.cleaned_data.get('manager_id') else: raise ValidationError(_('管理人不存在'), code='invalid')
class SellerForm(TOCForm): name_seller = fields.CharField(required=True, label="Nome do responsável") email_seller = fields.EmailField(required=True, widget=forms.EmailInput, label="E-mail") cellphone_seller = fields.CharField(required=True, label="Celular") cpf = fields.CharField(required=True, label="CPF do responsável") cnpj = fields.CharField(label="CNPJ do estabelecimento") password_seller = fields.CharField(required=False, widget=PasswordInput, label="Senha", min_length="6") confirm_seller = fields.CharField(required=False, widget=PasswordInput, label="Senha", min_length="6") accepts_newsletter_seller = forms.BooleanField( required=False, initial="checked", label="Aceita receber Newsletter") # PagarMe bank_code = fields.CharField(required=False, label="Código do Banco") agency = fields.CharField(required=False, label="Agência", max_length=5, min_length=5) account = fields.CharField(required=False, label="Conta Bancária", max_length=13, min_length=13) account_type = fields.CharField(required=False, label="Tipo de Conta") def clean(self): cleaned_data = super(SellerForm, self).clean() print(cleaned_data) # CPF cpf = str(cleaned_data.get('cpf')) if len(cpf) != 14: error_message = forms.ValidationError( "CPF digitado incorretamente") self.add_error('cpf', error_message) cpf_num = re.sub('[^0-9]', '', cpf) if not validate_cpf(cpf_num): error_message = forms.ValidationError( "CPF digitado incorretamente") self.add_error('cpf', error_message) # CNPJ cnpj = str(cleaned_data.get('cnpj')) if len(cnpj) != 18: error_message = forms.ValidationError( "CNPJ digitado incorretamente") self.add_error('cnpj', error_message) cellphone = str(cleaned_data.get('cellphone_seller')) if len(cellphone) < 10: error_message = forms.ValidationError( "Celular digitado incorretamente") self.add_error('cellphone_seller', error_message) # E-mail if "bank_code" not in cleaned_data: email_seller = str(cleaned_data.get('email_seller')) if BuyerProfile.objects.filter( email=email_seller) or SellerProfile.objects.filter( email=email_seller): error_message = forms.ValidationError( "Já existe uma conta com este e-mail") self.add_error('email_seller', error_message) password_seller = str(cleaned_data.get('password_seller')) confirm_seller = str(cleaned_data.get('confirm_seller')) if password_seller is not None and confirm_seller is not None: if password_seller != confirm_seller: error_message = forms.ValidationError("Senhas diferentes!") self.add_error('password_seller', error_message)