示例#1
0
文件: forms.py 项目: gurevnind/bsc
class UpdateProfile(forms.ModelForm):
    username = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    email_confirmation = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email')

    def clean_email(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')

        db_email = User.objects.filter(email=email).exclude(
            username=username).exclude(username=self.instance.username)

        if db_email:
            raise forms.ValidationError(
                'This email address is already in use. Please supply a different emails.'
            )
        return email

    def clean_username(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')
        db_username = User.objects.filter(username=username).exclude(
            email=self.instance.email)
        if db_username:
            raise forms.ValidationError(
                'This username is already in use. Please supply a different usernames.'
            )
        return username

    def clean_email_confirmation(self):
        email_confirmation = self.cleaned_data['email_confirmation']
        email = self.cleaned_data.get('email')
        if email != email_confirmation:
            raise forms.ValidationError("The two e-mails fields didn't match.")

    def save(self, commit=True):
        user = super(UpdateProfile, self).save(commit=False)
        user.username = self.cleaned_data['username']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user
示例#2
0
class RegistrationForm(forms.Form):
    username=forms.CharField(max_length=30,label="username",required=True,error_messages={'invalid':'Username should be unique'})
    email=forms.EmailField(label="emailid",required=True)
    password1=forms.CharField(max_length=30,widget=forms.PasswordInput(),label="password",required=True)
    password2=forms.CharField(max_length=30,widget=forms.PasswordInput(),label="password(again)",required=True)
    ID=forms.CharField(max_length=30,required=True,error_messages={'invalid':'ID should not be Unique and Non Empty'})
    resourceperson=forms.CharField(max_length=30,required=True,error_messages={'invalid':'Resource Person should not be Unique and Non Empty'})
    res_person_workplace=forms.CharField(max_length=30,required=False)
    def clean_username(self):
        u=self.cleaned_data['username']
        try:
            u=User.objects.get(username__exact=u)
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError("Username Already Exists . Please Try another name",code='invalid')
    def clean(self):
        p1=self.cleaned_data['password1']
        p2=self.cleaned_data['password2']
        if p1 is not None and p2 is not None:
            if p1 != p2:
                raise forms.ValidationError("Two passwords did not match")
            else:
                return self.cleaned_data
        else:
            raise forms.ValidationError("Both fields should match")
示例#3
0
class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def clean_email(self):
        email = self.cleaned_data.get('email')
        username = self.cleaned_data.get('username')

        if email and User.objects.filter(email=email).exclude(
                username=username).count():
            raise forms.ValidationError(u'Email addresses must be unique.')
        return email

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]

        user.is_active = False

        if commit:
            user.save()
            mail_sender(user.email)
        return user
示例#4
0
class RegistrationForm(UserCreationForm):

    email = forms.EmailField(required=True)

    class Meta:
        #cria uma instancia do model de usuarios do Django admin
        model = User

        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )
    
    #Salva os dados no formulario
    def save(self, commit=True):

        usuario = super(RegistrationForm, self).save(commit=False)
        
        #self.cleaned_data garante que ninguem injete sql no seu model
        usuario.first_name = self.cleaned_data['first_name']
        usuario.last_name = self.cleaned_data['last_name']
        usuario.email = self.cleaned_data['email']

        if commit:
            usuario.save()

        return usuario
示例#5
0
class UserForm(forms.ModelForm):
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='ชื่อผู้ใช้ ')
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='รหัสผ่าน ')
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='ชื่อจริง ')
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='นามสกุล ')
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        label='อีเมล์ ')

    class Meta:
        model = User
        fields = ['username', 'password', 'email', 'first_name', 'last_name']
        help_texts = {
            'username':
            str('Required. 30 characters or fewer. Usernames may contain alphanumeric, _, @, +, . and - characters.<br><br>'
                )
        }
示例#6
0
class UserRegistartionForm(forms.ModelForm):
    username = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Имя пользователя')
    first_name = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Имя')
    last_name = forms.CharField(
        max_length=40,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='Фамилия')
    email = forms.EmailField(
        max_length=100,
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        label='Email')
    password = forms.CharField(
        max_length=128,
        strip=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='Пароль')
    password2 = forms.CharField(
        max_length=128,
        strip=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='Повторите пароль')
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }

    class Meta:
        model = AllUsers
        fields = ('username', 'email')
示例#7
0
class RegisterForm(forms.Form):
    full_name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)
    password_confirm = forms.CharField(widget=forms.PasswordInput,
                                       required=True)

    def clean_password(self):
        password = self.cleaned_data.get('password', None)
        validate_password(password)
        return password

    def clean_password_confirm(self):
        password = self.cleaned_data.get('password_confirm', None)
        validate_password(password)
        return password

    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()
        pwd = cleaned_data.get("password")
        pwdc = cleaned_data.get("password_confirm")
        email = cleaned_data.get("email")
        full_name = cleaned_data.get("full_name")

        if MyUser.objects.filter(email=email).count() != 0:
            self.add_error('email', _('this user already exists'))

        if pwd != pwdc:
            msg = _("Mismatch passwords")
            self.add_error('password_confirm', msg)
class LoginForm(forms.Form):
    email = forms.EmailField(
        max_length=70,
        error_messages=my_default_errors,
        required=True,
        label='',
        widget=forms.TextInput(
            attrs={
                'placeholder': 'پست الکترونیک',
                'style': "margin-top: 0px; direction: ltr;",
                'class': "form-control register-inputs",
                'type': 'email'
            }))
    password = Password(max_length=50,
                        error_messages=my_default_errors,
                        label='',
                        widget=forms.PasswordInput(
                            attrs={
                                'placeholder': 'رمز عبور',
                                'style': "direction: ltr;",
                                'class': "form-control register-inputs",
                                'type': 'password'
                            }),
                        required=True)
    captcha = CaptchaField(label='',
                           error_messages=captcha_errors,
                           required=True)
示例#9
0
class RegistrationForm(forms.Form):
    username = forms.RegexField(
        regex=r'^\w+$',
        widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
        label=_("Username"),
        error_messages={
            'invalid':
            ("This value must contain only letters, numbers and underscores.")
        })
    email = forms.EmailField(
        widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
        label=("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs=dict(required=True, max_length=30, render_value=False)),
                                label=("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(
        attrs=dict(required=True, max_length=30, render_value=False)),
                                label=("Password (again)"))

    def clean_username(self):
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            _("The username already exists. Please try another one."))

    def clean(self):
        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 did not match."))
        return self.cleaned_data
示例#10
0
class RegisterForm(forms.Form):
    username = forms.CharField(min_length=6,
                               max_length=20,
                               validators=[UnicodeUsernameValidator])
    email = forms.EmailField(max_length=150)
    password = forms.CharField(label="密码", min_length=6, max_length=25)
    repeat_password = forms.CharField(label="确认密码")

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")
        repeat_password = cleaned_data.get("repeat_password")
        email = cleaned_data.get("email")
        if not password:
            raise forms.ValidationError("密码为空")
        if password != repeat_password:
            raise forms.ValidationError("两次密码输入不一致")
        users = Users.objects.filter(Q(username=username)
                                     | Q(email=email)).first()
        if users:
            if username == users.username:
                raise forms.ValidationError("用户名已存在")
            if email == users.email:
                raise forms.ValidationError("邮箱已被注册")
示例#11
0
class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    account_type = forms.CharField(max_length=30, required = False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')#
	class Meta:
		model = User
		fields = '__all__'
示例#12
0
class EnterEmailForm(Form):
    email = forms.EmailField(max_length=200, help_text='Required')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                u'Email address already exists on system.')
示例#13
0
class Add(forms.Form):
    Username = forms.CharField(label='Your name', max_length=100,initial=" ")
    Password=forms.CharField(widget=forms.PasswordInput,label="Password",initial=" ")
    Email = forms.EmailField(label="Email Id:", initial="",)
    age=forms.IntegerField(label="Your age")
    Description=forms.CharField(label="Describe Yourself",widget=forms.Textarea)
    
    Profile_Picture = forms.FileField(label="Your Profile Picture:")
示例#14
0
class GrocerySendMail(forms.Form):
    """Grocery form to send a grocery list to someone in email"""
    def __init__(self, data=None, files=None, request=None, *args, **kwargs):
        if request is None:
            raise TypeError("Keyword argument 'request must be supplies'")
        super(GrocerySendMail, self).__init__(data=data,
                                              files=files,
                                              *args,
                                              **kwargs)
        self.request = request

        # set up the return email address and sender name to the user logged in
        if request.user.is_authenticated():
            self.fields['to_email'].initial = request.user.email

    to_email = forms.EmailField(widget=forms.TextInput(),
                                label=_('email address'))
    gid = forms.CharField(widget=forms.HiddenInput())

    from_email = settings.DEFAULT_FROM_EMAIL
    from_site = ''
    #from_site = Site.objects.get_current()
    subject = _('Grocery list from ' + str(from_site))

    def get_body(self):
        """get the grocery list and return the message body for the email"""
        if self.is_valid():
            list = GroceryList.objects.get(pk=self.cleaned_data['gid'])
            template_name = 'list/grocery_mail_body.html'  # template that contains the email body and also shared by the grocery print view
            message = loader.render_to_string(template_name, {'list': list},
                                              context_instance=RequestContext(
                                                  self.request))
            return message
        else:
            raise ValueError(
                _('Can not get grocery list id from invalid form data'))

    def get_toMail(self):
        """gets the email to send the list to from the form"""
        if self.is_valid():
            return self.cleaned_data['to_email']
        else:
            raise ValueError(_('Can not get to_email from invalid form data'))

    def save(self, fail_silently=False):
        """ sends the email message"""
        if self.subject and self.get_body() and self.from_email:
            try:
                msg = EmailMessage(self.subject, self.get_body(),
                                   self.from_email, [self.get_toMail()])
                msg.content_subtype = 'html'
                msg.send()
            except BadHeaderError:
                return HttpResponse(_('Invalid header found.'))
            return HttpResponse(_('Email Sent'))
        else:
            return HttpResponse('Make sure all fields are entered and valid.')
示例#15
0
文件: forms.py 项目: molonc/colossus
class TenxGSCSubmissionForm(forms.Form):
    name = forms.CharField(max_length=50, widget=forms.TextInput())
    email = forms.EmailField(max_length=50, widget=forms.EmailInput())
    date = forms.DateField(widget=forms.SelectDateWidget(), initial=datetime.date.today())
    tenxpools = forms.ChoiceField(
        widget=forms.Select(),
        choices=[(pool.id, pool.pool_name) for pool in TenxPool.objects.all().order_by('id')],
        label="TenX Pool",
    )
示例#16
0
class RegUserForm(forms.Form):
    # akvo data
    gebied = forms.CharField(max_length=100)
    naam = forms.CharField(max_length=100)
    deviceid = forms.CharField(max_length=100)

    #acacia data
    voornaam = forms.CharField(label='voornaam', max_length=100)
    tussenvoegsel = forms.CharField(label='tussenvoegsel', max_length=100)
    achternaam = forms.CharField(label='achternaam', max_length=100)
    email = forms.EmailField()
    telefoon = forms.CharField()
示例#17
0
class Responsable_Form(forms.Form):
    Numero_Dni = forms.CharField(
        label='Numero de Dni',
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control input-sm',
            'placeholder': 'Numero DNI'
        }))
    Nombre_Responsable = forms.CharField(
        label='Nombres',
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control input-sm',
            'placeholder': 'Nombre Completo'
        }))
    Apellido_Paterno_Responsable = forms.CharField(
        label='Apellido Paterno',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))
    Apellido_Materno_Responsable = forms.CharField(
        label='Apellido Paterno',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))
    Nombre_Usuario = forms.CharField(
        label='Nombre Usuario',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))
    Email = forms.EmailField(
        label='Direccion Email',
        required=True,
        widget=forms.EmailInput(attrs={'class': 'form-control input-sm'}))
    Telefono = forms.CharField(
        label='Numero de telefono',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))
    Region = forms.ChoiceField(label='Region encargada',
                               required=True,
                               widget=forms.Select,
                               choices=choices_regiones)
    contra1 = forms.CharField(
        label='Contraseña',
        required=True,
        widget=forms.PasswordInput(attrs={'class': 'form-control input-sm'}))
    contra2 = forms.CharField(
        label='Confirmar contraseña',
        required=True,
        widget=forms.PasswordInput(attrs={'class': 'form-control input-sm'}))
    clave = forms.CharField(
        label='Clave Unica',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control input-sm'}))
示例#18
0
class EditProfileForm(forms.ModelForm):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='ชื่อจริง ')
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='นามสกุล ')
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        label='อีเมล์ ')

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
示例#19
0
文件: forms.py 项目: gurevnind/bsc
class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        username = self.cleaned_data.get('username')
        if email and User.objects.filter(email=email).exclude(
                username=username).exists():
            raise forms.ValidationError(u'Email addresses must be unique.')
        return email
class Forgot_password_getting_email(forms.Form):
    email = forms.EmailField(max_length=70,
                             error_messages=my_default_errors,
                             required=True,
                             label='',
                             widget=forms.TextInput(
                                 attrs={
                                     'placeholder': 'پست الکترونیک',
                                     'style': "direction: ltr;",
                                     'class': "form-control register-inputs",
                                     'type': 'email'
                                 }))
    captcha = CaptchaField(label='',
                           error_messages=captcha_errors,
                           required=True)
示例#21
0
class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200,
                             help_text='Required',
                             required=True)

    def clean_email(self):
        email = self.cleaned_data['email']
        username = self.cleaned_data['username']
        if email and User.objects.filter(email=email).exclude(
                username=username).exists():
            raise forms.ValidationError(u'Email addresses must be unique.')
        return email

    class Meta(UserCreationForm.Meta):
        model = User
        fields = UserCreationForm.Meta.fields + ('email', )
示例#22
0
class SignUpForm(UserCreationForm):

    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta(UserCreationForm.Meta):
        model = DonationUser

        fields = ('username', 'first_name', 'last_name', 'email', 'role', 'password1', 'password2', )

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.save()
        return user
示例#23
0
class SignUp(forms.Form):
    """ Sign Up """
    Name = forms.CharField(
        label="Your Name",
        widget=forms.TextInput(attrs={"placeholder": "It's Nice to meet you"}))
    username = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={"placeholder": "Make it Creative"}))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={"placeholder": "We wont sell it. "}),
        label="Password")
    email = forms.EmailField(label="Email Id")
    DateOfBirth = forms.DateField(label="Date of Birth")

    Bio = forms.CharField(widget=forms.Textarea(
        attrs={"placeholder": "Tell us about yourself"}))
    profilePic = forms.FileField()
示例#24
0
文件: forms.py 项目: detrout/OpenEats
    def __init__(self, data=None, files=None, request=None, *args, **kwargs):
        if request is None:
            raise TypeError("Keyword argument 'request must be supplies'")
        super(GrocerySendMail, self).__init__(data=data,
                                              files=files,
                                              *args,
                                              **kwargs)
        self.request = request

        # set up the return email address and sender name to the user logged in
        if request.user.is_authenticated():
            self.fields['to_email'].initial = request.user.email

        self.to_email = forms.EmailField(widget=forms.TextInput(),
                                         label=_('email address'))
        self.gid = forms.CharField(widget=forms.HiddenInput())

        self.from_email = settings.DEFAULT_FROM_EMAIL
        self.from_site = Site.objects.get_current()
        self.subject = _('Grocery list from ' + str(from_site))
示例#25
0
class RegisterForm(forms.Form):
    gender = (
        ('male', "男"),
        ('female', "女"),
    )
    username = forms.CharField(
        label="用户名",
        max_length=128,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    password1 = forms.CharField(
        label="密码",
        max_length=256,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    password2 = forms.CharField(
        label="确认密码",
        max_length=256,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(
        label="邮箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'}))
    sex = forms.ChoiceField(label='性别', choices=gender)
class RegistrationForm(forms.Form):
    username = forms.CharField(
        max_length=30,
        label="username",
        required=True,
        error_messages={'invalid': 'Username should be unique'})
    email = forms.EmailField(label="emailid", required=True)
    password1 = forms.CharField(max_length=30,
                                widget=forms.PasswordInput(),
                                label="password",
                                required=True)
    password2 = forms.CharField(max_length=30,
                                widget=forms.PasswordInput(),
                                label="password(again)",
                                required=True)
    options = [('teacher', 'Teacher'), ('student', 'Student')]
    role = forms.ChoiceField(widget=forms.RadioSelect(),
                             label="Account Type",
                             required=True,
                             choices=options)

    def clean_username(self):
        u = self.cleaned_data['username']
        try:
            u = User.objects.get(username__exact=u)
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(
            "Username Already Exists . Please Try another name",
            code='invalid')

    def clean(self):
        p1 = self.cleaned_data['password1']
        p2 = self.cleaned_data['password2']
        if p1 is not None and p2 is not None:
            if p1 != p2:
                raise forms.ValidationError("Two passwords did not match")
            else:
                return self.cleaned_data
        else:
            raise forms.ValidationError("Both fields should match")
示例#27
0
class Add(forms.Form):
    Username = forms.CharField(label='Your name', max_length=100, initial=" ")
    Password = forms.CharField(widget=forms.PasswordInput,
                               label="Password",
                               initial=" ")
    Email = forms.EmailField(
        label="Email Id:",
        initial="",
    )
    age = forms.IntegerField(label="Your age")
    Description = forms.CharField(label="Describe Yourself",
                                  widget=forms.Textarea)
    OPTIONS = (("Java", "Java"), ("C++", "C++"), ("C", "C"),
               ("Python", "Python"), ("JavaScript", "JavaScript"), ("Ruby",
                                                                    "Ruby"))
    Languages = forms.MultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple,
        choices=OPTIONS,
    )
    Profile_Picture = forms.FileField(label="Your Profile Picture:")
示例#28
0
class CustomUserAuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    email/password logins.
    """
    email = forms.EmailField(widget=forms.TextInput(attrs={'autofocus': True}))
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}),
    )

    error_messages = {
        'invalid_login':
        _("Please enter a correct %(email)s and password. Note that both "
          "fields may be case-sensitive."),
        'inactive':
        _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)

        # Set the max length and label for the "email" field.
        self.email_field = CustomUser._meta.get_field(CustomUser.EMAIL_FIELD)
        email_max_length = self.email_field.max_length or 254
        self.fields['email'].max_length = email_max_length
        self.fields['email'].widget.attrs['maxlength'] = email_max_length
        if self.fields['email'].label is None:
            self.fields['email'].label = capfirst(
                self.email_field.verbose_name)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email is not None and password:
            self.user_cache = authenticate(self.request,
                                           email=email,
                                           password=password)
            if self.user_cache is None:
                raise self.get_invalid_login_error()
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user(self):
        return self.user_cache

    def get_invalid_login_error(self):
        return forms.ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'email': self.email_field.verbose_name},
        )
示例#29
0
class UploadFileForm(forms.Form):
    name = forms.CharField(max_length=50)
    template = forms.DecimalField()
    photo = forms.ImageField()
    email = forms.EmailField()
    message = forms.CharField(max_length=500)
示例#30
0
class MyForm(forms.Form):
    email = forms.EmailField()