class UserCorporateForm(forms.Form): fName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) lName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) dob = forms.DateField(widget=forms.DateInput( attrs={ 'class': 'form-control', 'type': 'date', 'required': True, })) gender = forms.ChoiceField(choices=GENDER) email = forms.EmailField(validators=[EmailValidator], widget=forms.EmailInput(attrs={ 'class': 'form-control', 'required': True, })) phone = forms.CharField(validators=[telephone], widget=forms.TextInput( attrs={ 'class': 'form-control masked', 'data-format': '+255999999999', 'placeholder': 'Enter telephone', 'required': True, })) password = forms.CharField( validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'autocomplete': 'off', 'required': True, })) verify = forms.CharField(validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'required': True, })) id_type = forms.ChoiceField(choices=ID_TYPES) id_number = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True })) user_id = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'class': 'form-control', 'onchange': 'jQuery(this).next("input").val(this.value)', 'required': True })) notification = forms.BooleanField(required=False, widget=CheckboxInput(attrs={ 'id': 'notification', 'checked': '' })) checker = forms.BooleanField(widget=CheckboxInput( attrs={ 'class': 'checked-agree', 'id': 'checker', 'required': True })) def __init__(self, *args, **kwargs): super(UserCorporateForm, self).__init__(*args, **kwargs) for _, field in self.fields.iteritems(): if field in self.errors: field.widget.attrs.update({'autofocus': 'autofocus'}) break def clean(self): clean_data = self.cleaned_data phone = clean_data['phone'].replace('+255', '0', 1) if 'phone' in clean_data and Profile.objects.filter( msisdn=phone, profile_type='C').exists(): self.fields['phone'].widget.attrs['autofocus'] = 'autofocus' self.fields['phone'].widget.attrs['class'] = 'error' raise forms.ValidationError( "This phone number is already associated with another user!") if 'email' in clean_data and Profile.objects.filter( user__email=clean_data['email'], profile_type='C').exists(): self.fields['email'].widget.attrs['autofocus'] = 'autofocus' self.fields['email'].widget.attrs['class'] = 'error' self.add_error('email', 'Provide another email') raise forms.ValidationError( "This email is already associated with another user!") if 'password' in clean_data and 'verify' in clean_data and clean_data[ 'password'] != clean_data['verify']: self.fields['password'].widget.attrs['autofocus'] = 'autofocus' self.fields['password'].widget.attrs['class'] = 'error' self.fields['verify'].widget.attrs['class'] = 'error' raise forms.ValidationError("Passwords must be identical.") return clean_data def clean_user_id(self): identity = self.cleaned_data['user_id'] if identity: if identity.size > 5 * 1024 * 1024: self.fields['user_id'].widget.attrs['autofocus'] = 'autofocus' self.fields['user_id'].widget.attrs['class'] = 'error' raise ValidationError("Image file too large ( > 5mb )") return identity else: self.fields['user_id'].widget.attrs['autofocus'] = 'autofocus' self.fields['user_id'].widget.attrs['class'] = 'error' raise ValidationError("Couldn't read uploaded image")
class LoginForm(forms.Form): email = forms.EmailField(label="Email Address") password = forms.CharField(widget=forms.PasswordInput, min_length=8)
class EmailForm(forms.Form): name = forms.CharField(required=False) email = forms.EmailField()
class RegisterForm(forms.Form): email = forms.EmailField(required=True) password = forms.CharField(required=True, min_length=5) captcha = CaptchaField(error_messages={'invalid': '验证码错误'})
class UserLoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput)
class EmailFieldForm(ReprForm): _email = forms.EmailField()
class RegisterForm(forms.Form): username = forms.RegexField(max_length=30, regex=r"^[\w-]+$") email = forms.EmailField() password = forms.CharField(required=False) photo = forms.ImageField(required=False)
class CheckForm(forms.Form): ''' Form handling check ''' mail = forms.EmailField( label=_('E-Mail'), required=False, min_length=MIN_LENGTH_EMAIL, max_length=MAX_LENGTH_EMAIL, error_messages={ 'required': _('Cannot check without a domain name.') }) openid = forms.CharField( label=_('OpenID'), required=False, min_length=MIN_LENGTH_URL, max_length=MAX_LENGTH_URL, error_messages={ 'required': _('Cannot check without an openid name.') }) size = forms.IntegerField( label=_('Size'), initial=80, min_value=5, max_value=AVATAR_MAX_SIZE, required=True, ) default_opt = forms.ChoiceField( label=_('Default'), required=False, widget=forms.RadioSelect, choices = [ ('retro', _('Retro style (similar to GitHub)')), ('robohash', _('Roboter style')), ('pagan', _('Retro adventure character')), ('wavatar', _('Wavatar style')), ('monsterid', _('Monster style')), ('identicon', _('Identicon style')), ('mm', _('Mystery man')), ('none', _('None')), ], ) default_url = forms.URLField( label=_('Default URL'), min_length=1, max_length=MAX_LENGTH_URL, required=False, ) def clean(self): self.cleaned_data = super().clean() mail = self.cleaned_data.get('mail') openid = self.cleaned_data.get('openid') default_url = self.cleaned_data.get('default_url') default_opt = self.cleaned_data.get('default_opt') if default_url and default_opt and default_opt != 'none': if not 'default_url' in self._errors: self._errors['default_url'] = ErrorList() if not 'default_opt' in self._errors: self._errors['default_opt'] = ErrorList() errstring = _('Only default URL OR default keyword may be specified') self._errors['default_url'].append(errstring) self._errors['default_opt'].append(errstring) if not mail and not openid: raise ValidationError(_('Either OpenID or mail must be specified')) return self.cleaned_data
class EmailInputForm(forms.Form, BaseFormFieldPluginForm): """Form for ``EmailInputPlugin``.""" plugin_data_fields = [ ("label", ""), ("name", ""), ("help_text", ""), ("initial", ""), ("max_length", str(DEFAULT_MAX_LENGTH)), ("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} ) ) initial = forms.EmailField( 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, 'min': str(DEFAULT_MIN_LENGTH)}), initial=DEFAULT_MAX_LENGTH, validators=[MinValueValidator(DEFAULT_MIN_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} ) ) def clean(self): super(EmailInputForm, self).clean() max_length = self.cleaned_data.get('max_length', DEFAULT_MAX_LENGTH) if self.cleaned_data['initial']: len_initial = len(self.cleaned_data['initial']) if len_initial > max_length: self.add_error( 'initial', _("Ensure this value has at most {0} characters " "(it has {1}).".format(max_length, len_initial)) )
class UserRegistrationForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) full_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) sender = forms.EmailField() cc_myself = forms.BooleanField(required=False)
class UserLoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
class ContactForm(forms.Form): name = forms.CharField(label="Имя", widget=forms.TextInput) email = forms.EmailField(widget=forms.EmailInput) message = forms.CharField(label="Сообщение", widget=forms.Textarea)
class EditProfileForm(forms.Form): fName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) lName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) dob = forms.DateField(widget=forms.DateInput( attrs={ 'class': 'form-control', 'type': 'date', 'required': True, })) gender = forms.ChoiceField(choices=GENDER) client_id = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True })) scanned_id = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'id': 'file', 'class': 'form-control', 'onchange': 'jQuery(this).next("input").val(this.value)', 'required': True })) id_choice = forms.ChoiceField(choices=ID_TYPES) email = forms.EmailField(max_length=50, widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) phone = forms.CharField(validators=[telephone], widget=forms.TextInput( attrs={ 'class': 'form-control masked', 'data-format': '9999999999', 'placeholder': 'Enter telephone', 'required': True, })) bot_cds = forms.CharField(min_length=6, max_length=20, required=False, widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': False })) dse_cds = forms.CharField(min_length=6, max_length=20, required=False, widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': False })) password = forms.CharField( validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'autocomplete': 'off', 'required': True, })) verify = forms.CharField(validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'required': True, })) notification = forms.BooleanField(required=False, widget=CheckboxInput(attrs={ 'id': 'notification', 'checked': '' })) def clean(self): clean_data = self.cleaned_data if 'password' in clean_data and 'verify' in clean_data and clean_data[ 'password'] != clean_data['verify']: self.fields['password'].widget.attrs['autofocus'] = 'autofocus' self.fields['password'].widget.attrs['class'] = 'error' self.fields['verify'].widget.attrs['class'] = 'error' raise forms.ValidationError("Passwords must be identical.") return clean_data def clean_scanned_id(self): image = self.cleaned_data['scanned_id'] if image: if image.size > 5 * 1024 * 1024: self.fields['scanned_id'].widget.attrs[ 'autofocus'] = 'autofocus' self.fields['scanned_id'].widget.attrs['class'] = 'error' raise ValidationError("Image file too large ( > 5mb )") return image else: self.fields['scanned_id'].widget.attrs['autofocus'] = 'autofocus' self.fields['scanned_id'].widget.attrs['class'] = 'error' raise ValidationError("Couldn't read uploaded image")
class ContactForm(CDCForm): name = forms.CharField(max_length=100, label='Your name') email = forms.EmailField(max_length=200, label='Your email address') body = forms.CharField(widget=forms.Textarea, label='Your message') human = forms.CharField(max_length=100, label=False, required=False)
class EmailPostForm(forms.Form): name =forms.CharField(max_length=25) email=forms.EmailField() to=forms.EmailField() comments=forms.CharField(required=False,widget=forms.Textarea)
class SignupForm(forms.Form): username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(), 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=dict(maxlength=75)), label=_(u'email address'), required=False) # error_messages={'required': 'Please enter your email.'}) password = forms.CharField(widget=forms.PasswordInput(), 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 GeneralSettingsForm(SiteSettingsForm): """General settings for Review Board.""" CACHE_TYPE_CHOICES = ( ('memcached', _('Memcached')), ('file', _('File cache')), ) CACHE_BACKENDS_MAP = { 'file': 'django.core.cache.backends.filebased.FileBasedCache', 'memcached': 'django.core.cache.backends.memcached.CacheClass', 'locmem': 'django.core.cache.backends.locmem.LocMemCache', } CACHE_TYPES_MAP = { 'django.core.cache.backends.filebased.FileBasedCache': 'file', 'django.core.cache.backends.memcached.CacheClass': 'memcached', 'django.core.cache.backends.locmem.LocMemCache': 'locmem', } CACHE_LOCATION_FIELD_MAP = { 'file': 'cache_path', 'memcached': 'cache_host', } server = forms.CharField( label=_("Server"), help_text=_("The URL of this Review Board server. This should not " "contain the subdirectory Review Board is installed in."), widget=forms.TextInput(attrs={'size': '30'})) site_media_url = forms.CharField( label=_("Media URL"), help_text=_("The URL to the media files. Leave blank to use the " "default media path on this server."), required=False, widget=forms.TextInput(attrs={'size': '30'})) site_admin_name = forms.CharField( label=_("Administrator Name"), required=True, widget=forms.TextInput(attrs={'size': '30'})) site_admin_email = forms.EmailField( label=_("Administrator E-Mail"), required=True, widget=forms.TextInput(attrs={'size': '30'})) locale_timezone = TimeZoneField( label=_("Time Zone"), required=True, help_text=_("The time zone used for all dates on this server.")) search_enable = forms.BooleanField( label=_("Enable search"), help_text=_("Provides a search field for quickly searching through " "review requests."), required=False) max_search_results = forms.IntegerField( label=_("Max number of results"), help_text=_("Maximum number of search results to display."), min_value=1, required=False) search_results_per_page = forms.IntegerField( label=_("Search results per page"), help_text=_("Number of search results to show per page."), min_value=1, required=False) search_index_file = forms.CharField( label=_("Search index directory"), help_text=_("The directory that search index data should be stored " "in."), required=False, widget=forms.TextInput(attrs={'size': '50'})) cache_type = forms.ChoiceField( label=_("Cache Backend"), choices=CACHE_TYPE_CHOICES, help_text=_('The type of server-side caching to use.'), required=True) cache_path = forms.CharField( label=_("Cache Path"), help_text=_('The file location for the cache.'), required=True, widget=forms.TextInput(attrs={'size': '50'})) cache_host = forms.CharField( label=_("Cache Hosts"), help_text=_('The host or hosts used for the cache, in hostname:port ' 'form. Multiple hosts can be specified by separating ' 'them with a semicolon (;).'), required=True, widget=forms.TextInput(attrs={'size': '50'})) integration_gravatars = forms.BooleanField( label=_("Use Gravatar images"), help_text=_("Use gravatar.com for user avatars"), required=False) def load(self): domain_method = self.siteconfig.get("site_domain_method") site = Site.objects.get_current() # Load the rest of the settings from the form. super(GeneralSettingsForm, self).load() # Load the cache settings. cache_backend = normalize_cache_backend( self.siteconfig.get('cache_backend')) cache_type = self.CACHE_TYPES_MAP.get(cache_backend['BACKEND'], 'custom') self.fields['cache_type'].initial = cache_type if settings.DEBUG: self.fields['cache_type'].choices += ( ('locmem', _('Local memory cache')), ) if cache_type == 'custom': self.fields['cache_type'].choices += ( ('custom', _('Custom')), ) cache_locations = [] elif cache_type != 'locmem': cache_locations = cache_backend['LOCATION'] if not isinstance(cache_locations, list): cache_locations = [cache_locations] location_field = self.CACHE_LOCATION_FIELD_MAP[cache_type] self.fields[location_field].initial = ';'.join(cache_locations) # This must come after we've loaded the general settings. self.fields['server'].initial = "%s://%s" % (domain_method, site.domain) def save(self): server = self.cleaned_data['server'] if "://" not in server: # urlparse doesn't properly handle URLs without a scheme. It # believes the domain is actually the path. So we apply a prefix. server = "http://" + server url_parts = urlparse(server) domain_method = url_parts[0] domain_name = url_parts[1] if domain_name.endswith("/"): domain_name = domain_name[:-1] site = Site.objects.get_current() site.domain = domain_name site.save() self.siteconfig.set("site_domain_method", domain_method) cache_type = self.cleaned_data['cache_type'] if cache_type != 'custom': if cache_type == 'locmem': # We want to specify a "reviewboard" location to keep items # separate from those in other caches. location = 'reviewboard' else: location_field = self.CACHE_LOCATION_FIELD_MAP[cache_type] location = self.cleaned_data[location_field] if cache_type == 'memcached': # memcached allows a list of servers, rather than just a # string representing one. location = location.split(';') self.siteconfig.set('cache_backend', { DEFAULT_CACHE_ALIAS: { 'BACKEND': self.CACHE_BACKENDS_MAP[cache_type], 'LOCATION': location, } }) super(GeneralSettingsForm, self).save() # Reload any important changes into the Django settings. load_site_config() def full_clean(self): cache_type = self['cache_type'].data or self['cache_type'].initial for iter_cache_type, field in six.iteritems( self.CACHE_LOCATION_FIELD_MAP): self.fields[field].required = (cache_type == iter_cache_type) return super(GeneralSettingsForm, self).full_clean() def clean_cache_host(self): cache_host = self.cleaned_data['cache_host'].strip() if self.fields['cache_host'].required and not cache_host: raise ValidationError( _('A valid cache host must be provided.')) return cache_host def clean_cache_path(self): cache_path = self.cleaned_data['cache_path'].strip() if self.fields['cache_path'].required and not cache_path: raise ValidationError( _('A valid cache path must be provided.')) return cache_path def clean_search_index_file(self): """Validates that the specified index file is valid.""" index_file = self.cleaned_data['search_index_file'].strip() if index_file: if not os.path.isabs(index_file): raise ValidationError( _("The search index path must be absolute.")) if (os.path.exists(index_file) and not os.access(index_file, os.W_OK)): raise ValidationError( _('The search index path is not writable. Make sure the ' 'web server has write access to it and its parent ' 'directory.')) return index_file class Meta: title = _("General Settings") save_blacklist = ('server', 'cache_type', 'cache_host', 'cache_path') fieldsets = ( { 'classes': ('wide',), 'title': _("Site Settings"), 'fields': ('server', 'site_media_url', 'site_admin_name', 'site_admin_email', 'locale_timezone'), }, { 'classes': ('wide',), 'title': _('Cache Settings'), 'fields': ('cache_type', 'cache_path', 'cache_host'), }, { 'classes': ('wide',), 'title': _("Search"), 'fields': ('search_enable', 'max_search_results', 'search_results_per_page', 'search_index_file'), }, { 'classes': ('wide',), 'title': _("Third-party Integrations"), 'fields': ('integration_gravatars',), }, )
class ContactForm(forms.Form): email = forms.EmailField(label=_("Email")) subject = forms.CharField(label=_("Subject"), required=False) content = forms.CharField(label=_("Content"), widget=forms.Textarea()) template = "cmsplugin_contact/contact.html"
class RegForm(forms.Form): nombre = forms.CharField(max_length=100) email = forms.EmailField()
class UserRegistrationForm(forms.Form): email = forms.EmailField(max_length=254, error_messages={"required": "Email is required."}) username = forms.CharField( max_length=64, error_messages={"required": "Username is required."}) first_name = forms.RegexField( regex="^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$", max_length=64, error_messages={"required": "First name is required."}) last_name = forms.RegexField( regex="^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$", max_length=64, error_messages={"required": "Last name is required"}) password = forms.CharField( max_length=30, error_messages={"required": "Password is required"}, help_text="Password must be a strong password") conf_password = forms.CharField( max_length=30, error_messages={"required": "Confirm Password is required."}) phone = forms.RegexField(regex=r"^(\+63|0)9[0-9]{9}$", max_length=13, error_messages={ "invalid": "Phone number is invalid format", "required": "Mobile Phone is required." }) gender = forms.ChoiceField(choices=GENDER) birthdate = forms.DateField(input_formats=['%Y-%m-%d']) def clean(self): cd = super(UserRegistrationForm, self).clean() password = self.cleaned_data['password'] conf_password = self.cleaned_data['conf_password'] # (?=.*[a-hj-np-z])(?=.*[A-HJ-NP-Z])(?=.*(\d|!0)).{8,} if not re.match( '^(?=.*[a-z])(?=.*[A-Z])(?=.*[2-9])(?=.*(_|[^\w])).{8,}$', password): self.add_error( 'password', 'Password must contains alpha-numeric and special characters.') if len(password) < 8: self.add_error( 'password', 'Password must contains at least eight (8) alpha-numeric and special characters.' ) if password != conf_password: self.add_error('conf_password', 'Confirm Password not match.') return cd def clean_email(self): # Get the email email = self.cleaned_data.get('email', '') print("\n\n\nValidating Email address\n\n\n") # Check to see if any users already exist with this email as a username. try: match = User.objects.get(email=email) except User.DoesNotExist: # Unable to find a user, this is fine return email # A user was found with this as a username, raise an error. raise forms.ValidationError('This Email address is already in use.') def clean_username(self): # Get the email uname = self.cleaned_data.get('username', '') try: match = User.objects.get(username=uname) except User.DoesNotExist: # Unable to find a user, this is fine return uname # A user was found with this as a username, raise an error. raise forms.ValidationError('Username is already in use.') def clean_birthdate(self): today = date.today() cd = self.cleaned_data #bday = datetime.strptime(cd['birthdate'], "%m-%d-%Y").date() #print("\n\n\n\n\nBirthdate Format : {}\n\n\n\n".format(cd['birthdate'])) age = (today - cd['birthdate']) // timedelta(days=365.2425) if age < 18: self.add_error('birthdate', 'Birthdate must be atleast 18yrs old.') return cd['birthdate'] def save(self): #@w81mLBB01 cd = self.cleaned_data #username = cd['email'].split("@")[0] userdata = User.objects.create_user(username=cd['username'], email=cd['email'], password=cd['password']) userdata.first_name = cd['first_name'] userdata.last_name = cd['last_name'] userdata.is_staff = False userdata.is_active = True userprofile = UserProfile.objects.create(user_id=userdata.id, phone=cd['phone'], gender=cd['gender'], birthdate=cd['birthdate']) return userprofile.save()
class LoginForm(forms.Form): """user login form""" email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput())
class ForgetForm(forms.Form): email = forms.EmailField(required=True) captcha = CaptchaField(error_messages={'invalid': '验证码错误'})
class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email")
class GuestForm(forms.Form): email = forms.EmailField()
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")) captcha = CaptchaField() 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 UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2']
class EditUserForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput, label=_("Password")) email = forms.EmailField(label=_("Email"))
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 avoid defining a ``save()`` method -- the actual saving of collected user data is delegated to the active registration backend. """ username = forms.RegexField( regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Username"), required=True, error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") }) email = forms.EmailField( widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), required=True, label=_("Email address")) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), required=True, label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), required=True, label=_("Password (again)")) captcha = CaptchaField() def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address." )) return self.cleaned_data['email'] 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( _("A user with that username already exists.")) 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( _("The two password fields didn't match.")) return self.cleaned_data if 'email' in self.cleaned_data: self.clean_email()
class CorporateForm3(forms.Form): fName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) lName = forms.CharField(min_length=2, max_length=20, validators=[alphabetic], widget=forms.TextInput(attrs={ 'class': 'form-control', 'required': True, })) dob = forms.DateField(widget=forms.DateInput( attrs={ 'class': 'form-control', 'type': 'date', 'required': True, })) gender = forms.ChoiceField(choices=GENDER) email = forms.EmailField(validators=[EmailValidator], widget=forms.EmailInput(attrs={ 'class': 'form-control', 'required': True, })) phone = forms.CharField(validators=[telephone], widget=forms.TextInput( attrs={ 'class': 'form-control masked', 'data-format': '+255999999999', 'placeholder': 'Enter telephone', 'required': True, })) password = forms.CharField( validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'autocomplete': 'off', 'required': True, })) verify = forms.CharField(validators=[validate_slug], widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'required': True, })) def __init__(self, *args, **kwargs): super(CorporateForm3, self).__init__(*args, **kwargs) for _, field in self.fields.iteritems(): if field in self.errors: field.widget.attrs.update({'autofocus': 'autofocus'}) break def clean(self): clean_data = self.cleaned_data phone = clean_data['phone'].replace('+255', '0', 1) if 'phone' in clean_data and Profile.objects.filter( msisdn=phone, profile_type='C').exists(): self.fields['phone'].widget.attrs['autofocus'] = 'autofocus' self.fields['phone'].widget.attrs['class'] = 'error' raise forms.ValidationError( "This phone number is already associated with another user!") if 'email' in clean_data and Profile.objects.filter( user__email=clean_data['email'], profile_type='C').exists(): self.fields['email'].widget.attrs['autofocus'] = 'autofocus' self.fields['email'].widget.attrs['class'] = 'error' self.add_error('email', 'Provide another email') raise forms.ValidationError( "This email is already associated with another user!") if 'password' in clean_data and 'verify' in clean_data and clean_data[ 'password'] != clean_data['verify']: self.fields['password'].widget.attrs['autofocus'] = 'autofocus' self.fields['password'].widget.attrs['class'] = 'error' self.fields['verify'].widget.attrs['class'] = 'error' raise forms.ValidationError("Passwords must be identical.") return clean_data