class DenounceForm(forms.Form): number = forms.RegexField(max_length=12, required=True, regex='^\+[0-9]{11}$') the_hash = forms.CharField(max_length=100, required=True) comments = forms.CharField(required=False)
class RegisterForm(forms.Form): name = forms.CharField( max_length=20, required=True, error_messages={ 'required': '用户不能为空', 'invalid': '格式错误' }, label="用户名", label_suffix=':', widget=forms.TextInput(attrs={ 'class': 'f', 'placeholder': "please input name" })) password = forms.CharField( max_length=20, required=True, error_messages={ 'required': '密码不能为空', 'invalid': '格式错误' }, label="密码", label_suffix=":", widget=forms.PasswordInput(attrs={ 'class': 'f', 'placeholder': 'please input password' })) phone = forms.RegexField( required=True, regex= "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$", error_messages={ 'required': "电话不能为空", 'invalid': '格式错误' }, label="电话", label_suffix=":", widget=forms.TextInput(attrs={ 'class': 'f', 'placeholder': 'please input your phone' })) email = forms.RegexField( required=True, regex= "[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?", error_messages={ 'required': "邮箱不能为空", 'invalid': '格式错误' }, label="电子邮件", label_suffix=":", widget=forms.TextInput(attrs={ 'class': 'f', 'placeholder': 'please input your e-mail' })) idNumber = forms.RegexField( regex="^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$", required=True, error_messages={ 'required': "身份证不能为空", 'invalid': '格式错误' }, label="身份证号码", label_suffix=":", widget=forms.TextInput(attrs={ 'class': 'f', 'placeholder': 'please input your id number' })) country = forms.CharField( max_length=20, required=True, error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label="国家", label_suffix=":", widget=forms.TextInput( attrs={ 'class': 'f myCountry', 'placeholder': 'please input your country', 'id': 'myInput' }))
from django import forms from django.forms import ModelForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.db.models import Q username_regex_field = forms.RegexField( label='Username', max_length=30, regex=r'^[a-z0-9-_]+$', error_messages={ 'required': 'Please enter your name', 'invalid': 'Lowercase alphanumeric characters and underscores and dashes only (a-z, 0-9, _, -)' }, ) password_char_field = forms.CharField( label='Password', max_length=30, widget=forms.PasswordInput, ) confirm_password_char_field = forms.CharField( label='Confirm Password', max_length=30, widget=forms.PasswordInput, )
def test_validators_fail(self): field = SimpleArrayField(forms.RegexField('[a-e]{2}')) with self.assertRaises(exceptions.ValidationError) as cm: field.clean('a,bc,de') self.assertEqual(cm.exception.messages[0], 'Item 0 in the array did not validate: Enter a valid value.')
class UserCreationForm(UserForm, ColabSetPasswordFormMixin): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_email': _("Email already used. Is it you? " " Please <a href='%(url)s'>login</a>"), 'duplicate_username': _("A user with that username already exists."), 'password_mismatch': _("The two password fields didn't match."), } username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w]+$', help_text=_(("Required. 30 characters or fewer" ". Letter and digits.")), error_messages={ 'invalid': _(("This value may contain only" " letters and numbers."))}) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_(("Enter the same password as above" ", for verification."))) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True class Meta: model = User fields = ("username", "first_name", "last_name", "email") def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') user_qs = User.objects.filter(email=email).exclude(username=username) if email and user_qs.exists(): msg = self.error_messages.get('duplicate_email') % { 'url': reverse('login') } raise forms.ValidationError(mark_safe(msg)) return email def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"].strip() try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) super(UserCreationForm, self).clean_password2() return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) password = self.cleaned_data["password1"] user.set_password(password) if commit: user.save() user_created.send(user.__class__, user=user, password=password) return user
class RegisterForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_username': "******", 'password_mismatch': "The two password fields didn't match.", 'duplicate_email': "A user with this email already exists." } username = forms.RegexField( label='', max_length=150, regex=r'^[\w.@+-]+$', error_messages={ 'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."}, widget=forms.TextInput( attrs={ 'placeholder': 'Username', 'autofocus': 'autofocus' } ) ) email = forms.CharField( label='', max_length=254, widget=forms.EmailInput( attrs={'placeholder': 'Email'} ) ) password1 = forms.CharField( label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'Password', 'autocomplete': 'off' } ) ) password2 = forms.CharField( label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'Confirm Password', 'autocomplete': 'off' } ) ) captcha = get_captcha() class Meta: model = User fields = ("username", "email") def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) def clean_email(self): # Enforce unique email addresses for password recovery. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) validate_password(password2) return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class AddOrEditForm(forms.Form): poolname = forms.RegexField(max_length=50, initial="", regex=r'^[0-9a-zA-Z_\-]+$') addresses = forms.CharField(initial="") attribute = forms.ChoiceField(widget=forms.Select(), choices=ATTRIBUTE_CHOICES) attributevalues = forms.CharField(initial="", required=False) def fill(self, pool): self.initial['poolname'] = pool.poolname self.initial['addresses'] = pool.addresses self.initial['attribute'] = pool.attribute if pool.attribute is None: self.initial['attributevalues'] = "" else: self.initial['attributevalues'] = pool.attributevalues def update_pool(self, pool): pool.poolname = self.cleaned_data['poolname'] pool.addresses = self.cleaned_data['addresses'] if self.cleaned_data['attribute'] == 'None': pool.attribute = None pool.attributevalues = None else: pool.attribute = self.cleaned_data['attribute'] pool.attributevalues = self.cleaned_data['attributevalues'] pool.save() def is_valid(self): valid = super(AddOrEditForm, self).is_valid() return valid @property def my_poolname(self): return self.cleaned_data["poolname"] @my_poolname.setter def my_poolname(self, value): self.initial['poolname'] = value @property def my_addresses(self): return self.cleaned_data["addresses"] @my_addresses.setter def my_addresses(self, value): self.initial['addresses'] = value @property def my_attribute(self): return self.cleaned_data["attribute"] @my_attribute.setter def my_attribute(self, value): self.initial['attribute'] = value @property def my_attributevalues(self): return self.data["attributevalues"] @my_attributevalues.setter def my_attributevalues(self, value): self.initial['attributevalues'] = value
class PersonForm(forms.ModelForm): # title = forms.ChoiceField(choices=TITLES, required=False) # position = forms.CharField(required=False) # email = forms.EmailField() # department = forms.CharField(required=False) # supervisor = forms.CharField(required=False) telephone = forms.RegexField( "^[0-9a-zA-Z\.( )+-]+$", required=True, label=six.u("Office Telephone"), help_text=six.u( "Used for emergency contact and password reset service."), error_messages={ 'invalid': 'Telephone number may only contain digits, letter, ' 'hyphens, spaces, braces, and the plus sign.' }) mobile = forms.RegexField( "^[0-9a-zA-Z( )+-]+$", required=False, error_messages={ 'invalid': 'Telephone number may only contain digits, letter, ' 'hyphens, spaces, braces, and the plus sign.' }) fax = forms.CharField(required=False) address = forms.CharField(label=six.u("Mailing Address"), required=False, widget=forms.Textarea()) country = forms.ChoiceField(choices=COUNTRIES, initial='AU', required=False) def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['short_name'].help_text = \ "This is typically the person's given name. "\ "For example enter 'Fred' here." self.fields['full_name'].help_text = \ "This is typically the person's full name. " \ "For example enter 'Fred Smith' here." def clean(self): data = super(PersonForm, self).clean() for key in [ 'short_name', 'full_name', 'email', 'position', 'supervisor', 'department', 'telephone', 'mobile', 'fax', 'address', ]: if key in data and data[key]: data[key] = data[key].strip() return data class Meta: model = Person fields = [ 'short_name', 'full_name', 'email', 'title', 'position', 'supervisor', 'department', 'telephone', 'mobile', 'fax', 'address', 'country' ]
class RegistrationForm(forms.Form): username = forms.RegexField( label=_("Username"), max_length=30, regex=r'^[\w.-]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and ./-/_ characters.' ) }) email = forms.EmailField(label=_('E-mail')) email_repeat = forms.EmailField(label=_('E-mail (repeat)'), required=True) password = forms.CharField(label=_('Password'), widget=forms.PasswordInput(render_value=False)) password_repeat = forms.CharField( label=_('Password (repeat)'), widget=forms.PasswordInput(render_value=False)) first_name = forms.CharField(label=_('First name'), required=False) last_name = forms.CharField(label=_('Last name'), required=False) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) if not up_settings.DOUBLE_CHECK_EMAIL: del self.fields['email_repeat'] if not up_settings.DOUBLE_CHECK_PASSWORD: del self.fields['password_repeat'] if not up_settings.REGISTRATION_FULLNAME: del self.fields['first_name'] del self.fields['last_name'] if up_settings.EMAIL_ONLY: self.fields['username'].widget = forms.widgets.HiddenInput() self.fields['username'].required = False def _generate_username(self): """ Generate a unique username """ while True: # Generate a UUID username, removing dashes and the last 2 chars # to make it fit into the 30 char User.username field. Gracefully # handle any unlikely, but possible duplicate usernames. username = str(uuid.uuid4()) username = username.replace('-', '') username = username[:-2] try: User.objects.get(username=username) except User.DoesNotExist: return username def clean_username(self): if up_settings.EMAIL_ONLY: username = self._generate_username() else: username = self.cleaned_data['username'] if User.objects.filter(username__iexact=username): raise forms.ValidationError( _('A user with that username already exists.')) return username def clean_email(self): if not up_settings.CHECK_UNIQUE_EMAIL: return self.cleaned_data['email'] new_email = self.cleaned_data['email'] emails = User.objects.filter(email__iexact=new_email).count() if up_settings.USE_EMAIL_VERIFICATION: from userprofiles.contrib.emailverification.models import EmailVerification emails += EmailVerification.objects.filter( new_email__iexact=new_email, is_expired=False).count() if emails > 0: raise forms.ValidationError( _('This email address is already in use. Please supply a different email address.' )) return new_email def clean(self): if up_settings.DOUBLE_CHECK_EMAIL: if 'email' in self.cleaned_data and 'email_repeat' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data[ 'email_repeat']: raise forms.ValidationError( _('The two email addresses do not match.')) if up_settings.DOUBLE_CHECK_PASSWORD: if 'password' in self.cleaned_data and 'password_repeat' in self.cleaned_data: if self.cleaned_data['password'] != self.cleaned_data[ 'password_repeat']: raise forms.ValidationError( _('You must type the same password each time.')) return self.cleaned_data def save(self, *args, **kwargs): if up_settings.USE_ACCOUNT_VERIFICATION: from userprofiles.contrib.accountverification.models import AccountVerification new_user = AccountVerification.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password'], email=self.cleaned_data['email'], ) else: new_user = User.objects.create_user( username=self.cleaned_data['username'], password=self.cleaned_data['password'], email=self.cleaned_data['email']) if up_settings.REGISTRATION_FULLNAME: new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.save() if hasattr(self, 'save_profile'): self.save_profile(new_user, *args, **kwargs) return new_user
class SignupForm(forms.Form): """ Form for creating a new user account. Validates that the requested username and e-mail is not already in use. Also requires the password to be entered twice. """ username = forms.RegexField( regex=USERNAME_RE, max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Username"), error_messages={ 'invalid': _('Username must contain only letters, numbers, dots and underscores.' ) }) email = forms.EmailField( widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email")) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Create password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Repeat password")) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. Also validates that the username is not listed in ``USERENA_FORBIDDEN_USERNAMES`` list. """ try: user = get_user_model().objects.get( username__iexact=self.cleaned_data['username']) except get_user_model().DoesNotExist: pass else: if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter( user__username__iexact=self.cleaned_data['username'] ).exclude(activation_key=userena_settings.USERENA_ACTIVATED): raise forms.ValidationError( _('This username is already taken but not confirmed. Please check your email for verification steps.' )) raise forms.ValidationError(_('This username is already taken.')) if self.cleaned_data['username'].lower( ) in userena_settings.USERENA_FORBIDDEN_USERNAMES: raise forms.ValidationError(_('This username is not allowed.')) return self.cleaned_data['username'] def clean_email(self): """ Validate that the e-mail address is unique. """ if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']): if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter( user__email__iexact=self.cleaned_data['email']).exclude( activation_key=userena_settings.USERENA_ACTIVATED): raise forms.ValidationError( _('This email is already in use but not confirmed. Please check your email for verification steps.' )) raise forms.ValidationError( _('This email is already in use. Please supply a different email.' )) return self.cleaned_data['email'] def clean(self): """ Validates that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError( _('The two password fields didn\'t match.')) return self.cleaned_data def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1']) new_user = UserenaSignup.objects.create_user( username, email, password, not userena_settings.USERENA_ACTIVATION_REQUIRED, userena_settings.USERENA_ACTIVATION_REQUIRED) return new_user
class RegexInputForm(forms.Form, BaseFormFieldPluginForm): """Form for ``RegexInputPlugin``.""" plugin_data_fields = [ ("label", ""), ("name", ""), ("help_text", ""), ("initial", ""), ("regex", ""), ("max_length", "255"), ("required", False), ("placeholder", ""), ] label = forms.CharField( label=_("Label"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class})) name = forms.CharField(label=_("Name"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class})) help_text = forms.CharField( label=_("Help text"), required=False, widget=forms.widgets.Textarea( attrs={'class': theme.form_element_html_class})) regex = forms.RegexField( label=_("Regex"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class}), regex="", help_text=_("Enter a valid regular expression. A couple of common " "examples are listed below.<br/>" "- Allow a single digit from 1 to 9 (example value 6): " "<code>^[1-9]$</code><br/>" "- Allow any combination of characters from a to z, " "including capitals (example value abcXYZ):" "<code>^([a-zA-Z])+$</code><br/>" "- Allow a hex value (example value #a5c125:" "<code>^#?([a-f0-9]{6}|[a-f0-9]{3})$</code><br/>")) initial = forms.CharField( label=_("Initial"), required=False, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class})) max_length = forms.IntegerField( label=_("Max length"), required=True, widget=NumberInput(attrs={'class': theme.form_element_html_class}), initial=DEFAULT_MAX_LENGTH) required = forms.BooleanField( label=_("Required"), required=False, widget=forms.widgets.CheckboxInput( attrs={'class': theme.form_element_checkbox_html_class})) placeholder = forms.CharField( label=_("Placeholder"), required=False, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class}))
class VmaigPasswordRestForm(forms.Form): # 错误信息 error_messages = { 'email_error': u"此用户不存在或者用户名与email不对应.", } # 错误信息 invalid 表示username不合法的错误信息, # required 表示没填的错误信息 username = forms.RegexField(max_length=30, regex=r'^[\w.@+-]+$', error_messages={ 'invalid': u"该值只能包含字母、数字和字符@/./+/-/_", 'required': u"用户名未填" }) email = forms.EmailField(error_messages={ 'invalid': u"email格式错误", 'required': u'email未填' }) def clean(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if username and email: try: self.user = VmaigUser.objects.get(username=username, email=email, is_active=True) except VmaigUser.DoesNotExist: raise forms.ValidationError(self.error_messages["email_error"]) return self.cleaned_data def save(self, from_email=None, request=None, token_generator=default_token_generator): email = self.cleaned_data['email'] current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain uid = base64.urlsafe_b64encode(force_bytes( self.user.pk)).rstrip(b'\n=') token = token_generator.make_token(self.user) protocol = 'http' title = u"重置 {} 的密码".format(site_name) message = "".join([ u"你收到这封信是因为你请求重置你在网站 {} 上的账户密码\n\n".format(site_name), u"请访问该页面并输入新密码:\n\n", "{}://{}/resetpassword/{}/{}/\n\n".format(protocol, domain, uid, token), u"你的用户名,如果已经忘记的话: {}\n\n".format(self.user.username), u"感谢使用我们的站点!\n\n", u"{} 团队\n\n\n".format(site_name) ]) try: send_mail(title, message, from_email, [self.user.email]) except Exception as e: logger.error(u'[UserControl]用户重置密码邮件发送失败:[{}]/[{}]'.format( username, email))
class VmaigUserCreationForm(forms.ModelForm): # 错误信息 error_messages = { 'duplicate_username': u"此用户已存在.", 'password_mismatch': u"两次密码不相等.", 'duplicate_email': u'此email已经存在.' } # 错误信息 invalid 表示username不合法的错误信息, # required 表示没填的错误信息 username = forms.RegexField(max_length=30, regex=r'^[\w.@+-]+$', error_messages={ 'invalid': u"该值只能包含字母、数字和字符@/./+/-/_", 'required': u"用户名未填" }) email = forms.EmailField(error_messages={ 'invalid': u"email格式错误", 'required': u'email未填' }) password1 = forms.CharField(widget=forms.PasswordInput, error_messages={'required': u"密码未填"}) password2 = forms.CharField(widget=forms.PasswordInput, error_messages={'required': u"确认密码未填"}) class Meta: model = VmaigUser fields = ("username", "email") def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] try: VmaigUser._default_manager.get(username=username) except VmaigUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages["duplicate_username"]) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages["password_mismatch"]) return password2 def clean_email(self): email = self.cleaned_data["email"] # 判断是这个email 用户是否存在 try: VmaigUser._default_manager.get(email=email) except VmaigUser.DoesNotExist: return email raise forms.ValidationError(self.error_messages["duplicate_email"]) def save(self, commit=True): user = super(VmaigUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class CustomUserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'password_mismatch': _("The two password fields didn't match."), } username = forms.RegexField(label=_("Username (all lowercase)"), min_length=5, max_length=30, regex=r'^[\a-z.@+-]+$', help_text=_("Required. 5-30 lowercase characters. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only 5-30 lower case letters, numbers and " "@/./+/-/_ characters.")}) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification.")) sex = forms.ChoiceField(choices=(('Male', 'Male'), ('Female', 'Female'))) user_type = forms.ChoiceField(choices=(('Driver', 'Driver'), ('Passenger', 'Passenger'))) class Meta: # Point to our CustomUser here instead of default `User` model = CustomUser fields = ('full_name', 'short_name', 'email', 'sex', 'phone_number', 'user_type', 'address', 'username') def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] username = username.lower() try: # Refer to our CustomUser here instead of default `User` CustomUser._default_manager.get(username=username) except CustomUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch']) return password2 def save(self, commit=True): # Make sure we pass back in our CustomUserCreationForm and not the # default `UserCreationForm` user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class Registration_Form(UserCreationForm): username = forms.RegexField( label="Username", max_length=30, regex=r"^[\w.@+-]+$", help_text="Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only.", error_messages={ 'invalid': ("This value may contain only letters, numbers and " "@/./+/-/_ characters.") }, widget=TextInput( attrs={ 'class': 'form-control', 'required': 'true', 'placeholder': 'Enter your Username' })) password1 = forms.CharField(label="Password", widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'required': 'true', 'placeholder': 'Enter your password', })) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'required': 'true', 'placeholder': 'Enter your password again', }), help_text="Enter the same password as above, for verification.") email = forms.EmailField( label="Email", widget=forms.EmailInput( attrs={ 'class': 'form-control', 'required': 'true', 'placeholder': 'Enter your Email', }), help_text="Enter the same password as above, for verification.") last_name = forms.CharField( required=False, label="Last name ", label_suffix=" *not required", widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter your Last name', })) first_name = forms.CharField( required=False, label="First name ", label_suffix=" *not required", widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter your First name', })) birthday = forms.DateField( required=False, input_formats=['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'], initial=datetime.date.today, widget=forms.DateInput( attrs={ 'class': 'form-control', 'required': 'False', 'placeholder': 'RRRR/MM/DD', })) def save(self, commit=True): user = super(Registration_Form, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.birthday = self.cleaned_data['birthday'] Registration_Form.password = self.cleaned_data['password1'] user.set_password(Registration_Form.password) if commit: user.save() return user
class PioneerProfileForm(UserProfileForm): username = forms.RegexField( label=_("Username"), max_length=30, regex=r'^[\w.-]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and ./-/_ characters.' ) }) first_name = forms.CharField(label=_('First name'), required=False) last_name = forms.CharField(label=_('Last name'), required=False) error_messages = { 'password_mismatch': _("The two password fields didn't match."), 'password_incorrect': _('Your old password was entered incorrectly. ' 'Please enter it again.'), } old_password = forms.CharField(label=_('Old password'), required=False, widget=forms.PasswordInput) new_password1 = forms.CharField(label=_('New password'), required=False, widget=forms.PasswordInput) new_password2 = forms.CharField(label=_('New password confirmation'), required=False, widget=forms.PasswordInput) email = forms.EmailField(label=_("Email"), max_length=254) def __init__(self, *args, **kwargs): super(PioneerProfileForm, self).__init__(*args, **kwargs) self.fields['birth_date'].widget = DateL10nPicker() self.fields['email'].initial = self.instance.user.email self.fields['first_name'].initial = self.instance.user.first_name self.fields['last_name'].initial = self.instance.user.last_name self.fields['username'].initial = self.instance.user.username def clean_old_password(self): """ Validates that the old_password field is correct. """ old_password = self.cleaned_data['old_password'] if old_password and not self.instance.user.check_password( old_password): raise forms.ValidationError( self.error_messages['password_incorrect']) return old_password def clean_new_password2(self): """ Validates that the new password matches. """ password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch']) return password2 def save(self, commit=True): user = self.instance.user user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] new_password = self.cleaned_data['new_password1'] if new_password: user.set_password(new_password) if commit: user.save() return super(PioneerProfileForm, self).save(commit)
class WifiForm(ConnectionForm): """Form to create/edit a Wi-Fi connection.""" field_order = [ 'name', 'interface', 'zone', 'ssid', 'mode', 'band', 'channel', 'bssid', 'auth_mode', 'passphrase', 'ipv4_method', 'ipv4_address', 'ipv4_netmask', 'ipv4_gateway', 'ipv4_dns', 'ipv4_second_dns', 'ipv6_method', 'ipv6_address', 'ipv6_prefix', 'ipv6_gateway', 'ipv6_dns', 'ipv6_second_dns' ] ssid = forms.CharField(label=_('SSID'), help_text=_('The visible name of the network.')) mode = forms.ChoiceField(label=_('Mode'), choices=[('infrastructure', _('Infrastructure')), ('ap', _('Access Point')), ('adhoc', _('Ad-hoc'))]) band = forms.ChoiceField(label=_('Frequency Band'), choices=[('auto', _('Automatic')), ('a', _('A (5 GHz)')), ('bg', _('B/G (2.4 GHz)'))]) channel = forms.IntegerField( label=_('Channel'), help_text=_('Optional value. Wireless channel in the selected ' 'frequency band to restrict to. Blank or 0 value means ' 'automatic selection.'), min_value=0, max_value=255, required=False) bssid = forms.RegexField( label=_('BSSID'), help_text=_('Optional value. Unique identifier for the access point. ' 'When connecting to an access point, connect only if the ' 'BSSID of the access point matches the one provided. ' 'Example: 00:11:22:aa:bb:cc.'), regex=r'^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$', required=False) auth_mode = forms.ChoiceField( label=_('Authentication Mode'), help_text=_('Select WPA if the wireless network is secured and \ requires clients to have the password to connect.'), choices=[('wpa', _('WPA')), ('open', _('Open'))]) passphrase = forms.CharField(label=_('Passphrase'), validators=[validators.MinLengthValidator(8)], required=False) def __init__(self, *args, **kwargs): """Initialize the form, populate interface choices.""" super(WifiForm, self).__init__(*args, **kwargs) choices = self._get_interface_choices(nm.DeviceType.WIFI) self.fields['interface'].choices = choices def get_settings(self): """Return setting dict from cleaned data.""" settings = super().get_settings() settings['common']['type'] = '802-11-wireless' settings['wireless'] = { 'ssid': self.cleaned_data['ssid'], 'mode': self.cleaned_data['mode'], 'band': self.cleaned_data['band'], 'channel': self.cleaned_data['channel'], 'bssid': self.cleaned_data['bssid'], 'auth_mode': self.cleaned_data['auth_mode'], 'passphrase': self.cleaned_data['passphrase'], } return settings
class CreateProfileForm(forms.Form): full_name = forms.CharField(label=_('Full name'), max_length=50, widget=forms.TextInput(attrs={'size': '30'}), help_text='<span class="highlighted">*</span>') summary = forms.CharField( label=_('A short summary about you or your business'), max_length=300, widget=forms.Textarea(attrs={'class': 'short_textarea'}), help_text='<span class="highlighted">*</span>') email = forms.EmailField(label=_('Email'), max_length=100, widget=forms.TextInput(attrs={'size': '30'}), help_text='<span class="highlighted">*</span>') www = forms.URLField(required=False, max_length=100, widget=forms.TextInput(attrs={'size': '30'}), label=_('Home page')) phone = forms.RegexField(required=False, regex=r'^ *\+?[0-9.() -]*[0-9][0-9.() -]*$', label=_('Phone'), max_length=50, widget=forms.TextInput(attrs={'size': '15'})) fax = forms.CharField(required=False, label=_('Fax'), max_length=50, widget=forms.TextInput(attrs={'size': '15'})) address = forms.CharField( required=False, label=_('Address'), max_length=200, widget=forms.Textarea(attrs={'class': 'short_textarea'})) postal_code = forms.CharField(required=False, label=_('Postal code'), max_length=50, widget=forms.TextInput(attrs={'size': '15'})) country = forms.CharField(required=False, label=_('Country'), max_length=50, widget=forms.TextInput(attrs={'size': '30'})) time_zone = forms.CharField( label=_('Time zone'), max_length=300, widget=widgets.Select, help_text=('' if settings.CMBARTER_DEFAULT_USERS_TIME_ZONE else '<span class="highlighted">*</span>')) def clean_full_name(self): full_name = self.cleaned_data['full_name'].strip() if full_name: return full_name else: raise forms.ValidationError(_('This field is required.')) def clean_summary(self): summary = self.cleaned_data['summary'].strip() if summary: return summary else: raise forms.ValidationError(_('This field is required.')) def clean_www(self): return self.cleaned_data['www'].strip() def clean_phone(self): return self.cleaned_data['phone'].strip() def clean_fax(self): return self.cleaned_data['fax'].strip() def clean_address(self): return self.cleaned_data['address'].strip() def clean_postal_code(self): return self.cleaned_data['postal_code'].strip() def clean_country(self): return self.cleaned_data['country'].strip()
class SignupForm(forms.Form): username = forms.RegexField( regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs={'class': 'NB-input'}), label=_(u'username'), error_messages={ 'required': 'Please enter a username.', 'invalid': "Your username may only contain letters and numbers." }) email = forms.EmailField(widget=forms.TextInput(attrs={ 'maxlength': 75, 'class': 'NB-input' }), label=_(u'email address'), required=False) # error_messages={'required': 'Please enter your email.'}) password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'NB-input'}), label=_(u'password'), required=False) # error_messages={'required': 'Please enter a password.'}) def clean_username(self): username = self.cleaned_data['username'] return username def clean_password(self): if not self.cleaned_data['password']: return "" return self.cleaned_data['password'] def clean_email(self): if not self.cleaned_data['email']: return "" return self.cleaned_data['email'] def clean(self): username = self.cleaned_data.get('username', '') password = self.cleaned_data.get('password', '') exists = User.objects.filter(username__iexact=username).count() if exists: user_auth = authenticate(username=username, password=password) if not user_auth: raise forms.ValidationError( _(u'Someone is already using that username.')) return self.cleaned_data def save(self, profile_callback=None): username = self.cleaned_data['username'] password = self.cleaned_data['password'] exists = User.objects.filter(username__iexact=username).count() if exists: user_auth = authenticate(username=username, password=password) if not user_auth: raise forms.ValidationError( _(u'Someone is already using that username.')) else: return user_auth new_user = User(username=username) new_user.set_password(password) new_user.is_active = True new_user.email = self.cleaned_data['email'] new_user.save() new_user = authenticate(username=username, password=password) MActivity.new_signup(user_id=new_user.pk) if new_user.email: EmailNewUser.delay(user_id=new_user.pk) return new_user
class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should either preserve the base ``save()`` or implement a ``save()`` which accepts the ``profile_callback`` keyword argument and passes it through to ``RegistrationProfile.objects.create_inactive_user()``. """ username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_(u'username')) email = forms.EmailField( widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'email address')) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password')) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password (again)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ try: user = User.objects.get( username__iexact=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError( _(u'This username is already taken. Please choose another.')) def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError( _(u'You must type the same password each time')) return self.cleaned_data def save(self, profile_callback=None): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], profile_callback=profile_callback) return new_user
class ChasinViewsUserCreationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ error_messages = { 'duplicate_username': _("A user with that username already exists."), #'duplicate_email': _("A user with that email already exists."), 'password_mismatch': _("The two password fields didn't match."), } username = forms.RegexField( label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text=_("Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.") }) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above, for verification.")) class Meta: model = UserModel() #fields = ('email',) fields = ('username', ) def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] try: UserModel()._default_manager.get(username=username) except UserModel().DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) #def clean_email(self): # """ Clean form email. # # :return str email: cleaned email # :raise forms.ValidationError: Email is duplicated # """ # # Since EmailUser.email is unique, this check is redundant, # # but it sets a nicer error message than the ORM. See #13147. # email = self.cleaned_data["email"] # try: # get_user_model()._default_manager.get(email=email) # except get_user_model().DoesNotExist: # return email # raise forms.ValidationError( # self.error_messages['duplicate_email'], # code='duplicate_email', # ) def clean_password2(self): """ Check that the two password entries match. :return str password2: cleaned password2 :raise forms.ValidationError: password2 != password1 """ password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): """ Save user. Save the provided password in hashed format. :return custom_user.models.EmailUser: user """ user = super(ChasinViewsUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class EditProfileForm(forms.Form): email = forms.EmailField( required=False, label=_(u'email address'), help_text=_("We don't spam, and don't show your email to anyone")) username = forms.RegexField( label=_("Username"), max_length=30, regex=r'^(?u)[ \w.@+-]{4,}$', help_text= _("Required. 4-30 characters (only letters, numbers spaces and @/./+/-/_ characters)." ), error_message= _("Required. 4-30 characters (only letters, numbers spaces and @/./+/-/_ characters)." )) public_profile = forms.BooleanField( label=_('Public profile'), help_text=_('Allow other users to view your profile on the site'), required=False) gender = forms.ChoiceField(choices=GENDER_CHOICES, label=_('Gender')) description = forms.CharField( required=False, label=_('Tell us and other users bit about yourself'), widget=forms.Textarea(attrs={'rows': 3})) email_notification = forms.ChoiceField( choices=NOTIFICATION_PERIOD_CHOICES, label=_('E-Mail Notifications'), help_text= _('Should we send you e-mail notification about updates to things you follow on the site?' )) party = forms.ModelChoiceField( Party.objects.all(), required=False, label=_('(citizen) party member?'), help_text=_('Are you a member of any party?')) def __init__(self, user=None, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.user = user self.userprofile = user.get_profile() if self.user: self.initial = { 'username': user.username, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'public_profile': self.userprofile.public_profile, 'gender': self.userprofile.gender, 'description': self.userprofile.description, 'email_notification': self.userprofile.email_notification, 'party': self.userprofile.party, } self.has_email = True if user.email else False g, created = Group.objects.get_or_create(name='Valid Email') self.valid_email = g in self.user.groups.all() def clean_username(self): data = self.cleaned_data['username'] if data == self.user.username: return data try: User.objects.get(username=data) raise forms.ValidationError("This username is already taken.") except User.DoesNotExist: return data def clean(self): cleaned_data = self.cleaned_data return cleaned_data def save(self, commit=True): user = self.user if self.cleaned_data['email'] != None: if user.email != self.cleaned_data[ 'email']: #email changed - user loses comment permissions, until he validates email again. g = Group.objects.get(name='Valid Email') user.groups.remove(g) user.email = self.cleaned_data['email'] user.username = self.cleaned_data['username'] self.userprofile.gender = self.cleaned_data['gender'] self.userprofile.public_profile = self.cleaned_data['public_profile'] self.userprofile.description = self.cleaned_data['description'] self.userprofile.email_notification = self.cleaned_data[ 'email_notification'] self.userprofile.party = self.cleaned_data['party'] if commit: user.save() self.userprofile.save() return user
class BetaTestApplicationForm(NgModelFormMixin, NgFormValidationMixin, NgModelForm): """ Application form for beta testers. Creates instances of User, UserProfile, and BetaTestApplication models on submit. """ class Meta: model = BetaTestApplication exclude = ('user', 'status', 'instance', 'accepted_privacy_policy') widgets = { 'instance_name': TextInput, 'public_contact_email': EmailInput, 'project_description': Textarea, 'privacy_policy_url': URLInput, 'main_color': TextInput(attrs={'type': 'color'}), 'link_color': TextInput(attrs={'type': 'color'}), 'header_bg_color': TextInput(attrs={'type': 'color'}), 'footer_bg_color': TextInput(attrs={'type': 'color'}), } # Fields that can be modified after the application has been submitted can_be_modified = { 'full_name', 'subscribe_to_updates', 'main_color', 'link_color', 'header_bg_color', 'footer_bg_color', 'logo', 'favicon', 'privacy_policy_url', } # Fields that when modified need a restart of the instance needs_restart = { 'main_color', 'link_color', 'header_bg_color', 'footer_bg_color', 'logo', 'favicon', } full_name = forms.CharField( max_length=255, widget=TextInput, label='Your full name', help_text='Example: Albus Dumbledore', ) username = forms.RegexField( regex=r'^[\w.+-]+$', max_length=30, widget=TextInput, help_text=('This would also be the username of the administrator ' 'account on the Open edX instance.'), error_messages={ 'invalid': ('Usernames may contain only letters, numbers, and ' './+/-/_ characters.'), 'unique': 'This username is already taken.', }, ) email = forms.EmailField( widget=EmailInput, help_text=('This is also your account name, and where we will send ' 'important notices.'), ) password_strength = forms.IntegerField(widget=forms.HiddenInput, ) password = forms.CharField( strip=False, widget=PasswordInput, help_text=('Pick a password for your OpenCraft account. You will be ' 'able to use it to login and access your account.'), ) password_confirmation = forms.CharField( strip=False, widget=PasswordInput, help_text=('Please use a strong password: avoid common patterns and ' 'make it long enough to be difficult to crack.'), ) accept_terms = forms.BooleanField( required=True, help_text=('I accept that this is a free trial, ' 'and that the instance is provided without any guarantee.'), error_messages={ 'required': 'You must accept these terms to register.', }, ) accept_privacy_policy = forms.BooleanField( required=True, help_text=('I accept the privacy policy.'), error_messages={ 'required': 'You must accept the privacy policy to register.', }, ) subscribe_to_updates = forms.BooleanField( required=False, help_text= ('I want OpenCraft to keep me updated about important news, ' 'tips, and new features, and occasionally send me an email about it.' ), ) # This field is created automatically from the model field, but the regex # validator is not copied over. We need to define the field manually so # that validation will work client-side. We do this by copying from the # model field (DRY). _subdomain_field = Meta.model._meta.get_field('subdomain') _subdomain_validator = next(v for v in _subdomain_field.validators if hasattr(v, 'regex')) subdomain = forms.RegexField( regex=_subdomain_validator.regex, max_length=_subdomain_field.max_length, label=capfirst(_subdomain_field.verbose_name), help_text=_subdomain_field.help_text, error_messages={ 'invalid': _subdomain_validator.message, }, widget=TextInput(attrs={ 'class': 'input input--host input--host--subdomain text-xs-right', }), ) # Form values will be available in the angular scope under this namespace scope_prefix = 'registration' # This form itself will be available in the angular scope under this name form_name = 'form' def __init__(self, *args, **kwargs): """ If this form updates an existing application, populate fields from related models and make non-modifiable fields read only. """ # Save the request to be able to store notification messages later. # AJAX API calls for validation don't pass 'request'. if 'request' in kwargs: self.request = kwargs.pop('request') super().__init__(*args, **kwargs) if self.instance: if hasattr(self.instance, 'user'): # Populate the username and email fields and make them read only for field in ('username', 'email'): self.initial[field] = getattr(self.instance.user, field) self.fields[field].widget.attrs['readonly'] = True # Remove the password fields, the user already has a password del self.fields['password'] del self.fields['password_strength'] del self.fields['password_confirmation'] # If the user has a profile, populate the full_name field if hasattr(self.instance.user, 'profile'): self.initial[ 'full_name'] = self.instance.user.profile.full_name if self.instance.pk: # If the user has already registered they have already accepted # the terms, so the checkbox can default to checked self.initial['accept_terms'] = True self.initial[ 'subscribe_to_updates'] = self.instance.user.profile.subscribe_to_updates self.fields['accept_terms'].widget.attrs['checked'] = 'checked' self.initial['accept_privacy_policy'] = bool( self.instance.user.profile.accepted_privacy_policy) self.fields['accept_privacy_policy'].widget.attrs[ 'checked'] = 'checked' # Make all non-modifiable fields read only for name, field in self.fields.items(): if name not in self.can_be_modified: field.widget.attrs['readonly'] = True else: self.initial[ 'privacy_policy_url'] = settings.DEFAULT_PRIVACY_POLICY_URL def clean_subdomain(self): """ Strip the base domain from the end of the subdomain, if given. """ subdomain = self.cleaned_data.get('subdomain') if subdomain: match = subdomain.rfind('.' + BetaTestApplication.BASE_DOMAIN) if match != -1: return subdomain[:match] return subdomain def clean_username(self): """ Check that the username is unique. """ username = self.cleaned_data.get('username') if username and self._other_users.filter(username=username).exists(): raise forms.ValidationError( 'This username is already taken.', code='unique', ) return username def clean_email(self): """ Check that the email address is unique. """ email = self.cleaned_data.get('email') if email and self._other_users.filter(email=email).exists(): raise forms.ValidationError( 'This email address is already registered.', code='unique', ) return email def clean_password_strength(self): """ Check that client submitted password strength, and that value is in expected range. If there are issues, produce appropriate warnings but don't raise ValidationError (we don't want to display validation errors for this field to users). """ password_strength = self.cleaned_data.get('password_strength') if password_strength is None: logger.warning('Did not receive password strength from client.') elif password_strength not in range(5): logger.warning( 'Received suspicious value for password strength. ' 'Value should be in range [0, 4]. Observed value: {password_strength}', **{'password_strength': password_strength}) password_strength = None return password_strength def clean_password(self): """ Using score computed on the client, check that password is reasonably strong. """ password = self.cleaned_data.get('password') password_strength = self.cleaned_data.get('password_strength') if password and password_strength is not None and password_strength < 2: raise forms.ValidationError( ('Please use a stronger password: avoid common patterns and ' 'make it long enough to be difficult to crack.'), code='invalid', ) return password def clean_password_confirmation(self): """ Check that the password confirmation field matches the password field. """ password = self.cleaned_data.get('password') password_confirmation = self.cleaned_data.get('password_confirmation') if password and password_confirmation and password != password_confirmation: raise forms.ValidationError( "The two password fields didn't match.", code='password_mismatch', ) return password def clean(self): """ Only allow certain fields to be updated once the application has been submitted. """ cleaned_data = super().clean() if self.instance and self.instance.pk: return { field: value for field, value in cleaned_data.items() if field in self.can_be_modified } return cleaned_data def restart_fields_changed(self): """ Return true if any of the fields that need a restart were changed """ return any(field in self.changed_data for field in self.needs_restart) def save(self, commit=True): """ Create or update User, UserProfile, and BetaTestApplication instances with data from the form. """ application = super().save(commit=False) if hasattr(application, 'user'): self.update_user(application, commit=commit) else: self.create_user(application, commit=commit) return application def create_user(self, application, commit=True): """ Create related User and UserProfile instance for the given BetaTestApplication. """ user = User( username=self.cleaned_data['username'], email=self.cleaned_data['email'], ) user.set_password(self.cleaned_data['password']) profile = UserProfile( full_name=self.cleaned_data['full_name'], accepted_privacy_policy=timezone.now(), subscribe_to_updates=self.cleaned_data['subscribe_to_updates'], ) if commit: with transaction.atomic(): user.save() profile.user_id = user.pk application.user_id = user.pk profile.save() application.save() def update_user(self, application, commit=True): """ Update the UserProfile for the given application's user. Also detect changes in design fields, store them in instance, and notify us by e-mail. """ if hasattr(application.user, 'profile'): application.user.profile.full_name = self.cleaned_data['full_name'] application.user.profile.subscribe_to_updates = self.cleaned_data[ 'subscribe_to_updates'] application.user.profile.accepted_privacy_policy = timezone.now() else: application.user.profile = UserProfile( full_name=self.cleaned_data['full_name'], user_id=application.user.pk, subscribe_to_updates=self.cleaned_data['subscribe_to_updates'], accepted_privacy_policy=timezone.now(), ) if commit: with transaction.atomic(): application.user.profile.save() application.save() if self.restart_fields_changed(): if not application.email_addresses_verified(): messages.add_message( self.request, messages.INFO, "Thank you for submitting these changes - we will build your instance to " "apply them once your email address is verified.") return messages.add_message( self.request, messages.INFO, "Thank you for submitting these changes - we will rebuild your instance to " "apply them, and email you to confirm once it is up to date.") # Notify us if settings.VARIABLES_NOTIFICATION_EMAIL: subject = 'Update required at instance {name}'.format( name=application.subdomain, ) template = get_template( 'registration/fields_changed_email.txt') text = template.render( dict( application=application, changed_fields=self.changed_data, )) sender = settings.DEFAULT_FROM_EMAIL dest = [settings.VARIABLES_NOTIFICATION_EMAIL] send_mail(subject, text, sender, dest) def fields_with_errors(self): """ Returns a list of fields that did not pass validation, in a human-readable format. """ return [self[field].label for field in self.errors] @property def _other_users(self): """ Return a queryset for all users that are not the current user, if any. """ users = User.objects.all() if self.instance and self.instance.user_id: users = users.exclude(pk=self.instance.user_id) return users
class dMirrSignupForm(SignupForm): username = forms.RegexField(regex=USERNAME_RE, max_length=30, widget=forms.TextInput(attrs=ATTRS_DICT), label=_("Username"), error_messages={'invalid': _(ERROR_MSG)})
class FlatpageForm(TranslatableModelForm): slug = forms.RegexField( label=_("slug"), max_length=100, regex=r'^[-\w/\.~]+$', help_text= _("Example: '/about/contact/'. Make sure to have leading and trailing slashes." ), error_messages={ "invalid": _("This value must contain only letters, numbers, dots, " "underscores, dashes, slashes or tildes."), }, ) content = forms.CharField( widget=TinyMCE(attrs={ 'cols': 80, 'rows': 30 }, mce_attrs=settings.TINYMCE_DEFAULT_CONFIG)) class Meta: model = FlatPage # fields = '__all__' def clean_url(self): slug = self.cleaned_data['slug'] if not slug.startswith('/'): raise forms.ValidationError( ugettext("URL is missing a leading slash."), code='missing_leading_slash', ) if (settings.APPEND_SLASH and ('django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES) and not slug.endswith('/')): raise forms.ValidationError( ugettext("URL is missing a trailing slash."), code='missing_trailing_slash', ) return slug def clean(self): slug = self.cleaned_data.get('slug') sites = self.cleaned_data.get('sites') same_url = FlatPage.objects.language().filter(slug=slug) if self.instance.pk: same_url = same_url.exclude(pk=self.instance.pk) if sites and same_url.filter(sites__in=sites).exists(): for site in sites: if same_url.filter(sites=site).exists(): raise forms.ValidationError( _('Flatpage with url %(url)s already exists for site %(site)s' ), code='duplicate_url', params={ 'slug': slug, 'site': site }, ) return super(FlatpageForm, self).clean()
class InscriptionForm(forms.Form): parent_prenom = forms.CharField( required=True, max_length=200, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Prénom Parent"}), ) parent_nom = forms.CharField( required=True, max_length=200, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Nom Parent"}), ) enfant_prenom = forms.CharField( required=True, max_length=200, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Prénom"}), ) enfant_nom = forms.CharField( required=True, max_length=200, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Nom"}), ) enfant_ecole = forms.CharField( required=True, max_length=400, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"École"}), ) enfant_email = forms.EmailField( required=True, widget=forms.EmailInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Email"}), ) #enfant_age = forms.IntegerField( # required=True, # min_value=12, # max_value=22, # widget=forms.NumberInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"Âge"}) #) enfant_niveau_secondaire = forms.ChoiceField( required=True, choices=NIVEAU_SECONDAIRE, widget=forms.Select(attrs={"class":"form-control rounded-0",}) ) enfant_position = forms.ChoiceField( required=True, choices=POSITION_CHOIX, widget=forms.Select(attrs={"class":"form-control rounded-0",}) ) enfant_grandeur_tshirt = forms.ChoiceField( required=True, choices=GRANDEUR_TSHIRT_CHOIX, widget=forms.Select(attrs={"class":"form-control rounded-0",}) ) numero_telephone = forms.RegexField( required=True, regex=r'^\d{3}-\d{3}-\d{4}$', error_messages = {"invalid": "Vous devez entrer votre numéro de téléphone dans le format XXX-XXX-XXXX. Exemple: 418-666-1234"}, widget=forms.TextInput(attrs={"class":"form-control form-control-md rounded-0", "placeholder":"XXX-XXX-XXXX"}), ) decharge = forms.BooleanField( required=True, widget=forms.CheckboxInput(attrs={"class":"form-check-input mr-1",}) ) commentaires = forms.CharField( required=False, widget=forms.Textarea(attrs={"class":"form-control rounded-0 form-control-md","rows":"3", "placeholder":"Commentaires, Allergies, etc."}), )
class ForgetPwdForm(forms.Form): """Forget the password and try to find it""" email = forms.EmailField( label=u'用户邮箱', widget=forms.EmailInput(attrs={ 'class': 'form-control', 'id': 'email', 'placeholder': u'请输入您注册时用的邮箱' })) password1 = forms.RegexField( '^(?=.*[0-9])(?=.*[a-zA-Z]).{6,12}$', #这里正则匹配验证要求密码了里面至少包含字母、数字 label=u'新密码', min_length=6, max_length=12, error_messages={ 'required': '密码不能为空.', 'invalid': '密码必须至少包含数字和字母', 'min_length': "密码长度不能小于6个字符", 'max_length': "密码长度不能大于12个字符" }, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'id': 'password1', 'placeholder': u'请输入6-12位的密码' })) password2 = forms.CharField( label=u'确认密码', min_length=6, max_length=12, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'id': 'password2', 'placeholder': u'重复新的密码' })) check_code = forms.CharField( label=u'验证码', widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'check_code', 'placeholder': u'输入邮箱验证码' })) #验证邮箱是否存在 def clean_email(self): email = self.cleaned_data.get('email') users = models.User.objects.filter(email=email) if users.count() == 0: raise ValidationError(u'该邮箱没有被注册,请检查') return email #验证两个新密码是否一致 def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 != password2: raise ValidationError(u'两次输入的密码不一致') return password2 #验证验证码是否正确 def clean_check_code(self): #获取对应的用户 email = self.cleaned_data.get('email') check_code = self.cleaned_data.get('check_code') print("successful in check:email:{},check_code:{}", email, check_code) user = models.User.objects.filter(email=email) print("successful get email:{}", len(user)) #获取对应的用户拓展信息,验证验证码 user_ex = models.PWDReset.objects.filter(user=user) print("successful get code:{}", len(user_ex)) if len(user_ex) > 0: user_ex = user_ex[0] else: raise ValidationError(u'未获取验证码') if user_ex.valid_code != check_code: raise ValidationError(u'验证码不正确') print("valid code::{}", user_ex.valid_code) print("check code::{}", check_code) #验证有效期 now = timezone.now() #用这个回去当前时间 create_time = user_ex.valid_time #两个datetime相减,得到datetime.timedelta类型 td = now - create_time print("time second:", td.seconds) if td.seconds / 60 >= 10: #10分钟 print("time too long") raise ValidationError(u'验证码失效') print("final check code::{}", check_code) return check_code
class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'password_mismatch': _("The two password fields didn't match."), } user_login = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text=_("Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) user_pass = forms.CharField(label=_("Password"),widget=forms.PasswordInput) # user_email = forms.CharField(label='aaa',widget=forms.PasswordInput) # user_email= forms.EmailField(label=_("Email")) # user_pass2 = forms.CharField(label=_("Password confirmation"), #widget=forms.PasswordInput, # help_text=_("Enter the same password as above, for verification.")) class Meta: model = Users # fields = ("user_login","user_pass") #fields = '__all__' def clean_useremail(self): pass def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["user_login"] try: User._default_manager.get(user_login=username) except User.DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) def clean_password2(self): password1 = self.cleaned_data.get("user_pass") password2 = self.cleaned_data.get("user_pass") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["user_pass"]) if commit: user.save() return user
class AgencyForm(forms.Form): slug = forms.CharField(widget=forms.HiddenInput()) # Description description = forms.CharField( max_length=500, required=False, widget=forms.Textarea(attrs={ 'class': 'agency_description', 'maxlength': 500 })) # Public Liaison public_liaison_name = forms.CharField( label='Name', required=False, widget=forms.TextInput(attrs={'class': 'public_liaison_name'})) public_liaison_email = forms.EmailField( label='Email', required=False, widget=forms.EmailInput( attrs={ 'class': 'public_liaison_email', 'data-parsley-type-message': 'Please enter a valid email.' })) public_liaison_phone = forms.RegexField( label='Phone Number', required=False, regex=PHONE_RE, widget=forms.TextInput( attrs={ 'class': 'public_liaison_phone', 'data-parsley-pattern-message': 'Please enter a valid phone number.', 'pattern': PHONE_PATTERN })) # Request Center phone = forms.RegexField(label='Phone Number', required=False, regex=PHONE_RE, widget=forms.TextInput( attrs={ 'class': 'phone', 'data-parsley-pattern-message': 'Please enter a valid phone number.', 'pattern': PHONE_PATTERN })) # FOIA Request Submission address_line_1 = forms.CharField( label='Mailing address 1', required=False, widget=forms.TextInput(attrs={'class': 'address_line_1'})) address_line_2 = forms.CharField( label='Mailing address 2', required=False, widget=forms.TextInput(attrs={'class': 'address_line_2'})) city = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'city'})) state = USStateField(required=False, widget=forms.Select(choices=STATE_CHOICES, attrs={'class': 'state'})) zip_code = USZipCodeField(required=False, widget=forms.TextInput( attrs={ 'class': 'zip_code', 'data-parsley-pattern-message': 'Please enter a valid zip code.', 'pattern': '\d{5,5}(-\d{4,4})?' })) office_url = forms.URLField( label="Website URL", required=False, widget=forms.URLInput( attrs={ 'class': 'office_url', 'data-parsley-type-message': 'Please enter a valid url.', })) emails = forms.EmailField( label='Email', required=False, widget=forms.EmailInput( attrs={ 'class': 'email', 'data-parsley-type-message': 'Please enter a valid email.', })) fax = forms.RegexField(label='Fax Number', required=False, regex=PHONE_RE, error_message=('Must contain a valid phone number'), widget=forms.TextInput( attrs={ 'class': 'fax', 'data-parsley-pattern-message': 'Please enter a valid fax number.', 'pattern': PHONE_PATTERN })) # Other component_url = forms.URLField( label="Agency/component website", required=False, widget=forms.URLInput( attrs={ 'class': 'component_url', 'data-parsley-type-message': 'Please enter a valid url.', })) foia_libraries = forms.URLField( label="Reading room website", required=False, widget=forms.URLInput( attrs={ 'class': 'foia_libraries', 'data-parsley-type-message': 'Please enter a valid url.', })) regulations_website = forms.URLField( label="Regulations Website", required=False, widget=forms.URLInput( attrs={'data-parsley-type-message': 'Please enter a valid url.'})) common_requests = forms.CharField( label='Commonly requested topics', required=False, widget=forms.Textarea(attrs={ 'class': 'common_requests', 'maxlength': 500 })) no_records_about = forms.CharField( label='Commonly misdirected topics', required=False, widget=forms.Textarea(attrs={ 'class': 'no_records_about', 'maxlength': 500 })) request_instructions = forms.CharField( label='Request instructions', required=False, widget=forms.Textarea(attrs={ 'class': 'request_instructions', 'maxlength': 500 }))
class ConfirmForm(forms.Form): number = forms.RegexField(max_length=12, required=True, regex='^\+[0-9]{11}$') the_hash = forms.CharField(max_length=100, required=True)