我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.forms.EmailField()。
def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) ordering = [] if EMAIL_AUTHENTICATION: self.fields["email"] = forms.EmailField( label = ugettext("Email"), ) ordering.append("email") else: self.fields["username"] = forms.CharField( label = ugettext("Username"), max_length = 30, ) ordering.append("username") ordering.extend(["password", "remember"]) self.fields.keyOrder = ordering
def validate_cc_list(cc_list): '''Validate each email in cc_list argument This is called by ``notification_*`` methods internally. No return value, and if any email in cc_list is not valid, ValidationError will be raised. ''' if not isinstance(cc_list, list): raise TypeError('cc_list should be a list object.') field = EmailField(required=True) invalid_emails = [] for item in cc_list: try: field.clean(item) except ValidationError: invalid_emails.append(item) if invalid_emails: raise ValidationError( field.error_messages['invalid'] % { 'value': ', '.join(invalid_emails)})
def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs['max_length'] = kwargs.get('max_length', 254) super(EmailField, self).__init__(*args, **kwargs)
def deconstruct(self): name, path, args, kwargs = super(EmailField, self).deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs
def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. defaults = { 'form_class': forms.EmailField, } defaults.update(kwargs) return super(EmailField, self).formfield(**defaults)
def test(request): class CaptchaTestForm(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() captcha = CaptchaField(help_text='asdasd') return _test(request, CaptchaTestForm)
def test_model_form(request): class CaptchaTestModelForm(forms.ModelForm): subject = forms.CharField(max_length=100) sender = forms.EmailField() captcha = CaptchaField(help_text='asdasd') class Meta: model = User fields = ('subject', 'sender', 'captcha', ) return _test(request, CaptchaTestModelForm)
def test_custom_generator(request): class CaptchaTestModelForm(forms.ModelForm): subject = forms.CharField(max_length=100) sender = forms.EmailField() captcha = CaptchaField(generator=lambda: ('111111', '111111')) class Meta: model = User fields = ('subject', 'sender', 'captcha', ) return _test(request, CaptchaTestModelForm)
def test_non_required(request): class CaptchaTestForm(forms.Form): sender = forms.EmailField() subject = forms.CharField(max_length=100) captcha = CaptchaField(help_text='asdasd', required=False) return _test(request, CaptchaTestForm)
def test_id_prefix(request): class CaptchaTestForm(forms.Form): sender = forms.EmailField() subject = forms.CharField(max_length=100) captcha1 = CaptchaField(id_prefix="form1") captcha2 = CaptchaField(id_prefix="form2") return _test(request, CaptchaTestForm)
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
def to_python(self, value): value = super(EmailField, self).to_python(value) email = process_email(value) if not email: raise ValidationError('Enter a valid email address.', 'invalid') return email
def validate_url(url): protocols=[ 'http://', 'https://' ] flag=0 url_form_field = URLField() email_field = EmailField() try : email_field.clean(url) except ValidationError: if url!='': for protocol in protocols: n=len(protocol) if url[0:n]==protocol: flag=1 break if flag==0: flag1=1 for protocol in protocols: new_url = protocol+url try: new_url == url_form_field.clean(new_url) except ValidationError: flag1=0 else: url=new_url break if flag1==1: return True,url return False,url return True,url return False,url else: return False,url
def publish(self, user, id_string=None): if self.is_valid(): # If a text (csv) representation of the xlsform is present, # this will save the file and pass it instead of the 'xls_file' # field. if 'text_xls_form' in self.cleaned_data\ and self.cleaned_data['text_xls_form'].strip(): csv_data = self.cleaned_data['text_xls_form'] # "Note that any text-based field - such as CharField or # EmailField - always cleans the input into a Unicode string" # (https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.cleaned_data). csv_data = csv_data.encode('utf-8') # requires that csv forms have a settings with an id_string or # form_id _sheets = csv_to_dict(StringIO(csv_data)) try: _settings = _sheets['settings'][0] if 'id_string' in _settings: _name = '%s.csv' % _settings['id_string'] else: _name = '%s.csv' % _settings['form_id'] except (KeyError, IndexError) as e: raise ValueError('CSV XLSForms must have a settings sheet' ' and id_string or form_id') cleaned_xls_file = \ default_storage.save( upload_to(None, _name, user.username), ContentFile(csv_data)) else: cleaned_xls_file = self.cleaned_data['xls_file'] if not cleaned_xls_file: cleaned_url = self.cleaned_data['xls_url'] if cleaned_url.strip() == u'': cleaned_url = self.cleaned_data['dropbox_xls_url'] cleaned_xls_file = urlparse(cleaned_url) cleaned_xls_file = \ '_'.join(cleaned_xls_file.path.split('/')[-2:]) if cleaned_xls_file[-4:] != '.xls': cleaned_xls_file += '.xls' cleaned_xls_file = \ upload_to(None, cleaned_xls_file, user.username) self.validate(cleaned_url) xls_data = ContentFile(urllib2.urlopen(cleaned_url).read()) cleaned_xls_file = \ default_storage.save(cleaned_xls_file, xls_data) # publish the xls return publish_xls_form(cleaned_xls_file, user, id_string)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): if isinstance(field, forms.EmailField): field.widget = StrippedTextInput() if self.readonly: field.widget.attrs['readonly'] = 'readonly' field.widget.attrs['placeholder'] = \ '-- {0} --'.format(_('No information given'))
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LoginForm, self).__init__(*args, **kwargs) if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: login_widget = forms.TextInput(attrs={'type': 'email', 'placeholder': _('E-mail address'), 'autofocus': 'autofocus'}) login_field = forms.EmailField(label=_("E-mail"), widget=login_widget) elif app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME: login_widget = forms.TextInput(attrs={'placeholder': _('Username'), 'autofocus': 'autofocus'}) login_field = forms.CharField( label=_("Username"), widget=login_widget, max_length=get_username_max_length()) else: assert app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME_EMAIL login_widget = forms.TextInput(attrs={'placeholder': _('Username or e-mail'), 'autofocus': 'autofocus'}) login_field = forms.CharField(label=pgettext("field label", "Login"), widget=login_widget) self.fields["login"] = login_field set_form_field_order(self, ["login", "password", "remember"]) if app_settings.SESSION_REMEMBER is not None: del self.fields['remember']
def from_native(self, value): ret = super(EmailField, self).from_native(value) if ret is None: return None return ret.strip()
def test_should_email_convert_string(): assert_conversion(forms.EmailField, graphene.String)
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a User property. This defaults to a forms.EmailField instance, except if auto_current_user or auto_current_user_add is set, in which case None is returned, as such 'auto' fields should not be rendered as part of the form. """ if self.auto_current_user or self.auto_current_user_add: return None defaults = {'form_class': forms.EmailField} defaults.update(kwargs) return super(UserProperty, self).get_form_field(**defaults)
def __init__(self, request=None, *args, **kwargs): super(EmailAuthenticationForm, self).__init__(request, *args, **kwargs) del self.fields['username'] self.fields['email'] = forms.EmailField( label=('E-mail'), max_length=75) self.fields.insert(0, 'email', self.fields.pop('email'))
def add_fields(self, form, index): form.fields["email"] = EmailField(label=email_field_label)
def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: login_widget = forms.TextInput(attrs={'type': 'email', 'placeholder': _('E-mail address'), 'autofocus': 'autofocus'}) login_field = forms.EmailField(label=_("E-mail"), widget=login_widget) elif app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME: login_widget = forms.TextInput(attrs={'placeholder': _('Username'), 'autofocus': 'autofocus'}) login_field = forms.CharField( label=_("Username"), widget=login_widget, max_length=get_username_max_length()) else: assert app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME_EMAIL login_widget = forms.TextInput(attrs={'placeholder': _('Username or e-mail'), 'autofocus': 'autofocus'}) login_field = forms.CharField(label=pgettext("field label", "Login"), widget=login_widget) self.fields["login"] = login_field set_form_field_order(self, ["login", "password", "remember"]) if app_settings.SESSION_REMEMBER is not None: del self.fields['remember']
def clean(self): if 'password' in self.cleaned_data and 'confirm_password' in self.cleaned_data: if self.cleaned_data['password'] != self.cleaned_data['confirm_password']: raise forms.ValidationError(_("The two password fields did not match.")) return self.cleaned_data # class StudentInfoForm(forms.Form): # stud_name = forms.RegexField(required=True, regex=r'^\w+$', label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "First Name eg: Shiv", 'autofocus':'true'})) # stud_school = forms.RegexField(required=True, regex=r'^\w+$', label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "Student's School's Name"})) # stud_standard = forms.RegexField(required=True, regex=r'^\w+$', label='', max_length=30, widget=forms.TextInput(attrs={'placeholder': "Student's Standard"})) # stud_div = forms.RegexField(required=True, regex=r'^\w+$', label='', max_length=30, widget=forms.TextInput(attrs={'placeholder': "Student's Division"})) # # date_of_fill = forms.DateField(required=True, input_formats=['%d-%m-%Y'], label='',widget=forms.DateInput(attrs={'placeholder': "Date of Filling", 'type':"date"})) # date_of_birth = forms.DateField(required=True, input_formats=['%d-%m-%Y'], label='', widget=forms.DateInput(attrs={'placeholder': "Date of Birth", 'type':"date"})) # # father_name = forms.CharField(required=True, label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "Father's Full Name", 'autofocus':'true'})) # father_contact = forms.CharField(required=True, label='', max_length=10, widget=forms.TextInput(attrs={'placeholder': "Eg 98xxxxxxx0"})) # father_email = forms.EmailField(required=True, label='', widget=forms.TextInput(attrs=dict(required=True, max_length=200, placeholder="Father's Email"))) # father_education = forms.CharField(required=True, label='', max_length=200,widget=forms.TextInput(attrs={'placeholder': "Father's Education"})) # father_occupation = forms.CharField(required=True, label='', max_length=200,widget=forms.TextInput(attrs={'placeholder': "Father's Occupation"})) # # mother_name = forms.CharField(required=True, label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "Mother's Full Name",'autofocus': 'true'})) # mother_contact = forms.CharField(required=True, label='', max_length=10, widget=forms.TextInput(attrs={'placeholder': "Eg 98xxxxxxx0"})) # mother_email = forms.EmailField(required=True, label='', widget=forms.TextInput(attrs=dict(required=True, max_length=200, placeholder="Mother's Email"))) # mother_education = forms.CharField(required=True, label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "Mother's Education"})) # mother_occupation = forms.CharField(required=True, label='', max_length=200, widget=forms.TextInput(attrs={'placeholder': "Mother's Occupation"})) # # letter_identification = forms.BooleanField() # let_sound_assoc = forms.BooleanField() # spelling = forms.BooleanField() # reading = forms.BooleanField() # comprehension = forms.BooleanField() # composition = forms.BooleanField() # grammar = forms.BooleanField() # # number_identification = forms.BooleanField() # forget_tables = forms.BooleanField() # carry_borr = forms.BooleanField() # frac_dec = forms.BooleanField() # problem_int = forms.BooleanField() # algebra = forms.BooleanField() # # awareness = forms.IntegerField() # acceptance = forms.IntegerField() # active_participation = forms.IntegerField() # emo_support_provided = forms.IntegerField() # strength_awareness = forms.IntegerField() # parenting_style = forms.IntegerField()
def __init__(self, *args, **kwargs): email_required = kwargs.pop('email_required', app_settings.EMAIL_REQUIRED) self.username_required = kwargs.pop('username_required', app_settings.USERNAME_REQUIRED) super(BaseSignupForm, self).__init__(*args, **kwargs) username_field = self.fields['username'] username_field.max_length = get_username_max_length() username_field.validators.append( validators.MaxLengthValidator(username_field.max_length)) username_field.widget.attrs['maxlength'] = str( username_field.max_length) # field order may contain additional fields from our base class, # so take proper care when reordering... field_order = ['email', 'username'] if app_settings.SIGNUP_EMAIL_ENTER_TWICE: self.fields["email2"] = forms.EmailField( label=_("E-mail (again)"), widget=forms.TextInput( attrs={ 'type': 'email', 'placeholder': _('E-mail address confirmation') } ) ) field_order = ['email', 'email2', 'username'] merged_field_order = list(self.fields.keys()) if email_required: self.fields['email'].label = ugettext("E-mail") self.fields['email'].required = True else: self.fields['email'].label = ugettext("E-mail (optional)") self.fields['email'].required = False self.fields['email'].widget.is_required = False if self.username_required: field_order = ['username', 'email'] if app_settings.SIGNUP_EMAIL_ENTER_TWICE: field_order.append('email2') # Merge our email and username fields in if they are not # currently in the order. This is to allow others to # re-arrange email and username if they desire. Go in reverse # so that we make sure the inserted items are always # prepended. for field in reversed(field_order): if field not in merged_field_order: merged_field_order.insert(0, field) set_form_field_order(self, merged_field_order) if not self.username_required: del self.fields["username"]
def map_field(self, cfield): label = cfield.title if cfield.required: suffix = "*" if cfield.field_type == "string": f = forms.CharField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "text": f = forms.CharField(required=cfield.required, widget=forms.Textarea, label=label, label_suffix=suffix) elif cfield.field_type == "email": f = forms.EmailField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "boolean": f = forms.BooleanField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "number": f = forms.FloatField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "integer": f = forms.IntegerField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "select": f = forms.ChoiceField(required=cfield.required, choices=cfield.choices, label=label, label_suffix=suffix) elif cfield.field_type == "select_multiple": f = forms.MultipleChoiceField(required=cfield.required, choices=cfield.choices, label=label, label_suffix=suffix) elif cfield.field_type == "checkbox": f = forms.BooleanField(required=cfield.required, label=label, label_suffix=suffix) elif cfield.field_type == "radio": f = forms.ChoiceField(required=cfield.required, choices=cfield.choices, widget=forms.RadioSelect, label=label, label_suffix=suffix) else: # return a generic text input: f = forms.CharField() return f