def __init__(self, attrs=None, *args, **kwargs): """ Have to pass a list of field types to the constructor, else we won't get any data to our compress method. """ all_fields = ( fields.EmailField(max_length=75), fields.EmailField(max_length=75, label=_("Verfiy Email Address")), ) label = kwargs.pop('label', '') + ' (Enter twice to verify)' label = _(label) super(EmailVerificationField, self).__init__(all_fields, widget=EmailVerificationWidget(attrs={'class': 'form-control'}), label=label, *args, **kwargs)
class UserLoginForm(auth_forms.AuthenticationForm): username = fields.EmailField(widget=widgets.EmailInput( attrs={ 'class': 'form-control', 'placeholder': _('Email') })) password = fields.CharField(strip=False, widget=widgets.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': _('Mot de passe'), 'autocomplete': 'current-password' })) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') if email is None and password: raise forms.ValidationError( _("Veuillez entrer un email ainsi qu'un mot de passe")) if email and password: self.user_cache = authenticate(self.request, email=email, password=password) if self.user_cache: self.confirm_login_allowed(self.user_cache) else: raise forms.ValidationError( "Vous n'êtes pas autorisé à vous connecté") return self.cleaned_data
class Create(Form): email = fields.EmailField(required=True) password = fields.CharField(required=True) name = fields.CharField(required=True) surname = fields.CharField(required=True) phone = fields.CharField(required=False) is_active = BooleanField(required=False) is_vpn = BooleanField(required=False) source = EnumField(enum=User.Source, required=False) role = ModelChoiceField(to_field_name='name', queryset=Group.objects.all(), required=True) additional_data = AnyField(required=False) language_id = ModelChoiceField(queryset=Language.objects.all(), required=False) def clean_username(self): if User.objects.filter( username=self.cleaned_data['username']).exists(): raise ValidationError( _('User with this username already exists!')) return self.cleaned_data['username'] def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise ValidationError( _('User with this email already exists!')) return self.cleaned_data['email']
class DuskenUserForm(forms.ModelForm): first_name = fields.CharField(label=_('First name')) last_name = fields.CharField(label=_('Last name')) email = fields.EmailField( label=_('Email'), widget=forms.EmailInput(attrs={'placeholder': _('Email')})) phone_number = PhoneNumberField(label=_('Phone number')) password = fields.CharField(label=_('Password'), widget=forms.PasswordInput()) captcha = ReCaptchaField(label='') def clean_email(self): email = self.cleaned_data['email'] if email_exists(email): raise ValidationError(_('Email already in use')) return email def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if phone_number_exist(phone_number): raise ValidationError(_('Phone number already in use')) return phone_number def clean_password(self): password = self.cleaned_data['password'] validate_password(password) return password class Meta: model = DuskenUser fields = [ 'first_name', 'last_name', 'email', 'phone_number', 'password' ]
class FM(forms.Form): user = fields.CharField( error_messages={'required': '用户名不能为空'}, label='用户名', widget=widgets.Input( attrs={'class': 'c1'} ), #其实就是类型,可以是input 可以是textarea,可以是select; attrs 为该标签加上class=c1的样式 # widget=widgets.Textarea ) pwd = fields.CharField( max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, #自定义错误提示信息 label='密码', widget=widgets.PasswordInput) email = fields.EmailField( error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }, label='邮箱', ) f = fields.FileField(allow_empty_file=False) city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class UserCreateForm(UserCreationForm): first_name = fields.CharField(required=True, max_length=30) last_name = fields.CharField(required=True, max_length=30) email = fields.EmailField(required=True) class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user def clean_username(self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError("Username is taken.")
class Mybasisform(forms.Form): user = fields.CharField( # required=True 表不能為空 max_length=18, min_length=6, required=True, # 錯誤信息 error_messages={ 'required': '用戶名不能為空', 'max_length': '太長拉~', 'min_length': '太短拉~', }) pwd = fields.CharField(min_length=10, required=True, error_messages={ 'required': '密碼不能為空', 'min_length': '太短拉~', }) age = fields.IntegerField( required=True, error_messages={ 'required': '年齡不能為空', 'invalid': '必須為數字格式', # invalid 所有的格式錯誤都是用它 }) email = fields.EmailField( required=True, error_messages={ 'required': '信箱不能為空', 'invalid': '信箱格式錯誤', # invalid 所有的格式錯誤都是用它 })
class RegisterForm(django_forms.Form): username = django_fields.CharField(widget=django_widgets.TextInput( attrs={ 'class': 'form-control', 'placeholder': "请输入用户名", 'id': 'username' })) email = django_fields.EmailField(widget=django_widgets.EmailInput( attrs={ 'class': 'form-control', 'placeholder': "请输入邮箱", 'id': 'email' })) password = django_fields.CharField(widget=django_widgets.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "请输入密码", 'id': 'password' })) password2 = django_fields.CharField(widget=django_widgets.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "请再次输入密码", 'id': 'password2' })) code = django_fields.CharField(widget=django_widgets.TextInput( attrs={ 'class': 'form-control', 'placeholder': "请输入验证码", 'id': 'code' }))
class FM(forms.Form): # 通过form生成HTML页面 user = fields.CharField( error_messages={'required': '用户名不能为空'}, widget=widgets.Textarea(attrs={'class': 'c1'}), label='用户名', ) pwd = fields.CharField(max_length=32, min_length=6, error_messages={ 'required': '密码不能为空', 'min_length': '密码最少为6个字符', 'max_length': '密码最多为32个字符' }, widget=widgets.PasswordInput(attrs={'class': 'c2'})) email = fields.EmailField(error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }) f = fields.FileField(allow_empty_file=True) city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class RegisterForm(Form): username = fields.CharField(required=True, min_length=3, max_length=100, error_messages={ "required": "USER NAME EMPTY", "min_length": "TOO SHORT", "max_length": "TOO LONG" }) password = fields.CharField(required=True, min_length=3, max_length=18, error_messages={ "required": "PASSWORD CAN NOT EMPTY", "min_length": "PASSWORD TOO SHORT", "max_length": "PASSWORD TOO LONG" }) # password_2 = fields.CharField(required=False) email = fields.EmailField( required=True, error_messages={"required": "MAIL ERROR"}, ) def clean_password2(self): if not self.errors.get("password"): if self.cleaned_data["password2"] != self.cleaned_data["password1"]: raise ValidationError("NEED SAME PASSWORD") return self.cleaned_data
class RegisterForm(Form): username = fields.CharField(required=True, min_length=3, max_length=18, error_messages={ "required": "用户名不可以为空!", "min_length": "用户名不能低于3位!", "max_length": "用户名不能超过18位!" }) password1 = fields.CharField(required=True, min_length=3, max_length=18, error_messages={ "required": "密码不可以空", "min_length": "密码不能低于3位!", "max_length": "密码不能超过18位!" }) password2 = fields.CharField(required=False) email = fields.EmailField( required=True, error_messages={"required": "邮箱不可以为空!"}, ) def clean_password2(self): if not self.errors.get("password1"): if self.cleaned_data["password2"] != self.cleaned_data["password1"]: raise ValidationError("您输入的密码不一致,请重新输入!") return self.cleaned_data
class UserForm(Form): id = forms.CharField(required=True) username = forms.CharField(required=True) name = forms.CharField(required=True) sex = fields.CharField(required=True) phone = fields.CharField(required=True) email = fields.EmailField(required=True) card_id = fields.CharField(required=True) home_address = fields.CharField(required=True) desc = fields.CharField(required=False, ) def clean(self): if not self.errors.get("username"): data = User.objects.filter( username=self.cleaned_data['username']).first() if data and data.id != self.cleaned_data['id']: raise ValidationError("用户名已存在") if not self.errors.get("phone"): data = User.objects.filter( phone=self.cleaned_data['phone']).first() if data and data.id != self.cleaned_data['id']: raise ValidationError("手机号已存在") if not self.errors.get("email"): data = User.objects.filter( email=self.cleaned_data['email']).first() if data and data.id != self.cleaned_data['id']: raise ValidationError("邮箱已存在") return self.cleaned_data
class F1Form(forms.Form): #required 默认不为空 user = fields.CharField(max_length=18, min_length=6, required=True, error_messages={ "required": "用户名不能为空", "max_length": "用户名太长了", "min_length": "用户名太短了", }) pwd = fields.CharField(required=True, min_length=6, error_messages={ "required": "密码不能为空", "min_length": "密码太短了", }) age = fields.IntegerField(required=True) email = fields.EmailField(required=True, min_length=8, error_messages={ "required": "邮箱不能为空", "min_length": "密码太短了", "invalid": "邮箱格式错误" }) city = fields.ChoiceField( choices=[(1, "上海"), (2, "广州")], initial=1 #默认选择 ) bobby = fields.MultipleChoiceField(choices=[(1, "刚良"), (2, "附件"), (3, "你的")], )
class RegisterForm(forms.Form): username = fields.CharField( required=True, widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': '用户名'}), strip=True, error_messages={'required': '用户名不能为空'}, ) email = fields.EmailField( required=True, widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': '请输入邮箱'}), error_messages={'required': '邮箱不能为空','invalid':'请输入正确的邮箱格式'}, ) password = fields.CharField( widget=widgets.PasswordInput(attrs={'class': "form-control",'placeholder': '请输入密码'},render_value=True), required=True, strip=True, error_messages={'required': '密码不能为空!'}, ) confirm_password = fields.CharField( #render_value会对于PasswordInput,错误是否清空密码输入框内容,默认为清除,我改为不清楚 widget=widgets.PasswordInput(attrs={'class': "form-control",'placeholder': '请再次输入密码!'},render_value=True), required=True, strip=True, error_messages={'required': '请再次输入密码!'} )
class UserRegisterForm(forms.Form): user_name = fields.CharField(min_length=5, max_length=50) # password = fields.CharField(min_length=6, max_length=50) # 密码密文*输出 password = fields.Field(widget=widgets.PasswordInput()) real_name = fields.CharField(min_length=2, max_length=50) mail = fields.EmailField(min_length=6, max_length=50) # ap:管理员权限、pp:项目权限、mp:模块权限、gp:普通权限 # permission = fields.CharField(max_length=50) # permission = forms.ChoiceField(label="选择框",choices=(("ap","管理员权限"), # ("pp","项目权限"), # ("mp","模块权限"), # ("gp","普通权限"),)) # class UserLoginForm(forms.ModelForm): # # class Meta: # # model = User # # fields = ['user_name', 'password',] # class UserRegisterForm(forms.ModelForm): # # class Meta: # # model = User # # fields = ['user_name', 'password', 'real_name', 'mail']
class ForgetPasswordForm(forms.Form): email = fields.EmailField( required=True, widget=widgets.TextInput(attrs={ 'class': "form-control", 'placeholder': '请输入邮箱' }), # strip=True, error_messages={ 'required': '邮箱不能为空', 'invalid': '请输入正确的邮箱格式' }, ) username = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': "form-control", 'placeholder': '请输入用户名' }), min_length=6, max_length=12, strip=True, error_messages={ 'required': '用户名不能为空', })
class UserForm(forms.Form): username = fields.CharField( required=True, error_messages={'required': '用户名不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}) # 生成什么HTML插件 ) # 正则表达式,生成HTML标签 password = fields.CharField( required=True, error_messages={'required': '密码不能为空'}, widget=widgets.TextInput( attrs={'class': 'form-control'})) # 正则表达式,生成HTML标签 email = fields.EmailField( required=True, error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }, widget=widgets.EmailInput( attrs={'class': 'form-control'})) # 正则表达式,生成HTML标签 ut_id = fields.IntegerField( required=True, widget=widgets.Select( attrs={'class': 'form-control'}, # choices=[(1,'普通用户'),(2,"超级用户")]) # 第一步 # choices=UserType.objects.values_list('id', 'name') # 第二步 )) # 解决增加用户类型时,需要重启服务 def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['ut_id'].widget.choices = UserType.objects.values_list( 'id', 'name') # 第三步
class Expansion(forms.Form): username = fields.CharField() email = fields.EmailField() # ---------自定義單體驗證方法(clean_加字段名),必須有返回值--------- # clean_方法只能對當前字段進行驗證 def clean_username(self): """ 單體錯誤信息,存放在各自字段名(username) """ v = self.cleaned_data['username'] # 當前用戶提交的username if models.UserInfo.objects.filter(username=v).count(): # 判斷有沒有重名 # 有重名,錯誤 raise ValidationError('用戶名已存在') # 必須使用ValidationError拋出錯誤 return v # ---------自定義全體驗證方法(clean),必須有返回值--------- def clean(self): """ 整體錯誤信息,存放在__all__ """ value_dict = self.cleaned_data v1 = value_dict.get('username') v2 = value_dict.get('email') if v2.startswith(v1): raise ValidationError('整體錯誤信息,信箱和用戶名過於近似') return value_dict
class GuestForm(DialogModelForm): scope_prefix = 'data.guest' form_name = 'customer_form' # Override form name to reuse template `customer-form.html` legend = _("Customer's Email") email = fields.EmailField(label=_("Email address")) class Meta: model = get_user_model() # since we only use the email field, use the User model directly fields = ('email',) def __init__(self, initial=None, instance=None, *args, **kwargs): if isinstance(instance, CustomerModel): instance = instance.user super(GuestForm, self).__init__(initial=initial, instance=instance, *args, **kwargs) @classmethod def form_factory(cls, request, data, cart): customer_form = cls(data=data, instance=request.customer.user) if customer_form.is_valid(): customer_form.save() return customer_form def clean_email(self): # check for uniqueness of email address if get_user_model().objects.filter(is_active=True, email=self.cleaned_data['email']).exists(): msg = _("A registered customer with the e-mail address '{email}' already exists.\n" "If you have used this address previously, try to reset the password.") raise ValidationError(msg.format(**self.cleaned_data)) return self.cleaned_data['email']
class F1Form(forms.Form): username = fields.CharField(max_length=18, min_length=6, required=True, error_messages={ 'required': '用户名不能为空', 'max_length': '太长了', 'min_length': '太短了' }) pwd = fields.CharField(min_length=32, required=True, error_messages={ 'required': '密码不能为空', 'invalid': '密码长度为32位' }) age = fields.IntegerField(required=True, error_messages={ 'required': '不能为空', 'invalid': '必须为数字' }) email = fields.EmailField(required=True, min_length=8, error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误', 'max_length': '最小长度为8位' })
class Login_Form(forms.Form): email = fields.EmailField(label='email', required=True, error_messages={'invalid': 'invalid input'}) password = fields.CharField(label='password', max_length=128, required=True, widget=forms.PasswordInput) class Meta: app_label = 'mysite' def clean_email(self): get_email = self.cleaned_data.get("email") email_is_exist = Member_Model.objects.filter(email=get_email).exists() if not email_is_exist: raise forms.ValidationError('email does not exist') return get_email def clean_password(self): get_email = self.cleaned_data.get("email") get_password = self.cleaned_data.get("password") # password_is_correct = Member_Model.objects.filter(email=get_email,password=get_password).exists() # if not password_is_correct: # raise forms.ValidationError('email or password is wrong') return get_password
class InfoForm(Form): """完善信息Form""" # """修改信息Form""" activist_email = fields.EmailField( max_length=32, error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式有误!'}, widget=fields.TextInput(attrs={'class': 'form-control', 'placeholder': "请输入邮箱"}) ) activist_phone = fields.RegexField( regex=r"^1[356789]\d{9}$", max_length=32, error_messages={'required': '手机号码不能为空', 'invalid': '手机号码格式有误!'}, widget=fields.TextInput(attrs={'class': 'form-control', 'placeholder': "请输入手机号码"}) ) apply_date = forms.DateField( error_messages={'required': '申请入党日期不能为空'}, widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}) ) voluntary_time = fields.IntegerField( error_messages={'required': '志愿时长不能为空!'}, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': "请输入正整数的时长"}) )
class FM(forms.Form): # 字段本身只做验证 user = fields.CharField( error_messages={'required': '用户名不能为空.'}, widget=widgets.Textarea(attrs={'class': 'c1'}), label="用户名", ) pwd = fields.CharField(max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, widget=widgets.PasswordInput(attrs={'class': 'c2'})) email = fields.EmailField(error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }) f = fields.FileField() # p = fields.FilePathField(path='app01') city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class LoginForm1(BaseForm, django_forms.Form): username = django_fields.CharField(min_length=6, max_length=32, error_messages={ 'required': '用户名不能为空.', 'min_length': "用户名长度不能小于6个字符", 'max_length': "用户名长度不能大于32个字符" }) password1 = django_fields.CharField(min_length=8, max_length=32, error_messages={ 'required': '密码不能为空.', 'invalid': '密码必须包含数字,字母、特殊字符', 'min_length': "密码长度不能小于8个字符", 'max_length': "密码长度不能大于32个字符" }) password2 = django_fields.CharField(min_length=8, max_length=32, error_messages={ 'required': '密码不能为空.', 'invalid': '密码必须包含数字,字母、特殊字符', 'min_length': "密码长度不能小于8个字符", 'max_length': "密码长度不能大于32个字符" }) email = django_fields.EmailField(error_messages={ 'required': '邮箱不能为空.', }) check_code = django_fields.CharField( error_messages={'required': '验证码不能为空.'}) def clean_check_code(self): if self.request.session.get('CheckCode').upper( ) != self.request.POST.get('check_code').upper(): raise ValidationError(message='验证码错误', code='invalid')
class RegisterForms(forms.Form): username = fields.CharField( error_messages={'required':'用户名不能为空'} ) email = fields.EmailField( error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'} ) password = fields.CharField( error_messages={'required':'密码不能为空', }, ) code = fields.CharField( error_messages={'required': '验证码不能为空'} ) def clean_password(self): cleaned_data = self.cleaned_data password = cleaned_data['password'].replace(' ','') if len(password) < 6: raise forms.ValidationError("密码长度不能小于6个字符") return password # python匹配中文需要转换成unicode字符串 def clean_username(self): cleaned_data = self.cleaned_data reg_username = cleaned_data['username'] pattern = re.compile(u'^[\u4e00-\u9fa5_a-zA-Z0-9-]{3,16}$') match = pattern.match(unicode(reg_username)) if match: return reg_username else: raise forms.ValidationError("用户名长度为3~16个字符,支持中文,数字,字母,下划线,横杠")
class FM(forms.Form): user = fields.CharField(error_messages={'required': '用户名不能为空'}, widget=widgets.Input(attrs={'class': 'c1'}), label="用户名") pwd = fields.CharField(max_length=12, min_length=6, error_messages={ 'required': '密码不能为空', 'max_length': '密码长度不能大于12位', 'min_length': '密码长度不能小于6位' }, widget=widgets.PasswordInput(attrs={'class': 'c2'}), label="密码") email = fields.EmailField(error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }, label="邮箱") f = fields.FileField(allow_empty_file=False) p = fields.FilePathField(path='app01') # 列出app01目录下所有文件 city1 = fields.ChoiceField(choices=[(0, '北京'), (1, '吉林'), (2, '银川')]) city2 = fields.MultipleChoiceField(choices=[(0, '广东'), (1, '深圳'), (2, '东莞')])
class UserForm(Form): username = fields.CharField( required=True, error_messages={'required': '用户名不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) password = fields.CharField(required=True, error_messages={ 'required': '密码不能为空', 'invalid': '密码格式错误' }) email = fields.EmailField(required=True, error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }) phone = fields.IntegerField(required=True, error_messages={'required': '电话不能为空'}) sl_id = fields.MultipleChoiceField(choices=[], widget=widgets.SelectMultiple()) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['sl_id'].choices = models.Service_Line.objects.values_list( 'id', 'service_line_name')
class UserCreationEmailUniqueForm(UserCreationForm): """ Form for user creation to ensure uniqueness of email. """ error_messages = { 'duplicate_email': _("A user with that email already exists."), } email = fields.EmailField(label=_("E-mail address"), required=True) class Meta: model = User fields = ( 'username', 'email', ) def clean_email(self): """ Ensure that email is not yet used. """ email = self.cleaned_data["email"] try: User.objects.get(email=email) except User.DoesNotExist: return email raise ValidationError(self.error_messages['duplicate_email'])
class CustomerForm(DialogModelForm): scope_prefix = 'data.customer' legend = _("Customer's Details") email = fields.EmailField(label=_("Email address")) first_name = fields.CharField(label=_("First Name")) last_name = fields.CharField(label=_("Last Name")) class Meta: model = CustomerModel exclude = ('user', 'recognized', 'number', 'last_access',) custom_fields = ('email', 'first_name', 'last_name',) def __init__(self, initial=None, instance=None, *args, **kwargs): initial = dict(initial) if initial else {} assert instance is not None initial.update(dict((f, getattr(instance, f)) for f in self.Meta.custom_fields)) super(CustomerForm, self).__init__(initial=initial, instance=instance, *args, **kwargs) def save(self, commit=True): for f in self.Meta.custom_fields: setattr(self.instance, f, self.cleaned_data[f]) return super(CustomerForm, self).save(commit) @classmethod def form_factory(cls, request, data, cart): customer_form = cls(data=data, instance=request.customer) if customer_form.is_valid(): customer_form.instance.recognize_as_registered(request, commit=False) customer_form.save() return customer_form
class UserForm(fforms.Form): username = fields.CharField(required=True, max_length=32) email = fields.EmailField(required=True, max_length=32) city = fields.ChoiceField( choices=[(1, '广州'), (2, '上海'), (3, '北京')], initial=2, )