Exemple #1
0
class RegisterForm(UserCreationForm):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'username',
                # 'placeholder': 'username',
            }),
        required=True)

    first_name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'first_name',
                # 'placeholder': 'username',
            }),
        required=True)

    last_name = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'id': 'last_name',
                # 'placeholder': 'username',
            }),
        required=True)

    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        required=True)

    password1 = forms.CharField(
        label="Password",
        strip=False,
        widget=forms.PasswordInput(attrs={
            'autocomplete': 'new-password',
            'class': 'form-control'
        }),
        help_text=password_validation.password_validators_help_text_html(),
    )
    password2 = forms.CharField(
        label="Password confirmation",
        widget=forms.PasswordInput(attrs={
            'autocomplete': 'new-password,',
            'class': 'form-control'
        }),
        strip=False,
    )

    def clean(self):
        super()

    def clean_username(self):
        username = self.cleaned_data.get('username')
        qs = User.objects.filter(username=username)
        if qs.exists():
            raise forms.ValidationError('Username is taken')
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if 'gmail.com' not in email:
            raise forms.ValidationError('Email has to be gmail.com')

        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError('Email is taken')

        return email
Exemple #2
0
class CreateUserForm(forms.ModelForm):
    username = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'username',
        'class': 'form-control'
    }),
                               label='User Name')
    first_name = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'first_name',
        'class': 'form-control'
    }),
                                 label='First Name')
    last_name = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'last_name',
        'class': 'form-control'
    }),
                                label='Last Name')
    email = forms.CharField(widget=forms.EmailInput(attrs={
        'id': 'email',
        'class': 'form-control'
    }),
                            label='Email Address')
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='Password')
    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='Confirm Password')
    department = forms.ChoiceField(choices=EMPLOYEE_CHOICES,
                                   widget=forms.Select(attrs={
                                       'id': 'department',
                                       'class': 'form-control'
                                   }),
                                   label="Department",
                                   initial='')
    designation = forms.ChoiceField(
        choices=EMPLOYEE_CHOICES,
        widget=forms.Select(attrs={
            'id': 'designation',
            'class': 'form-control'
        }),
        label="Designation",
        initial='')
    mobile = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'mobile',
        'class': 'form-control'
    }),
                             label='Mobile',
                             max_length=10)
    address1 = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'address1',
        'class': 'form-control'
    }),
                               label='Address1',
                               max_length=255)
    address2 = forms.CharField(widget=forms.TextInput(attrs={
        'id': 'address1',
        'class': 'form-control'
    }),
                               label='Address2',
                               max_length=255)

    class Meta:
        model = User
        fields = [
            'username', 'first_name', 'last_name', 'email', 'department',
            'designation', 'password1', 'password2', 'mobile', 'address1',
            'address2'
        ]

    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 address already exists')
        return email

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if not password2:
            raise forms.ValidationError("You must confirm your password")
        if password1 != password2:
            raise forms.ValidationError("Your passwords do not match")
        return password2
Exemple #3
0
class RegisterForm(UserCreationForm):
    username = forms.CharField(
        label='Username*',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Username'
        }))
    email = forms.EmailField(
        label='Email*',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Email'
        }))
    first_name = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Firstname'
        }))
    last_name = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Lastname'
        }))
    password1 = forms.CharField(
        label='Enter Password*',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Password'
        }))
    password2 = forms.CharField(
        label='Confirm Password*',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Password'
        }))
    botfield = forms.CharField(required=False,
                               widget=forms.HiddenInput(),
                               validators=[validators.MaxLengthValidator(0)])

    def clean_email(self):
        email_field = self.cleaned_data.get('email')
        if User.objects.filter(email=email_field).exists():
            raise forms.ValidationError('Email already exist')
        return email_field

    class Meta():
        model = User
        fields = [
            'username', 'email', 'first_name', 'last_name', 'password1',
            'password2'
        ]

    def save(self, commit=True):
        user = super().save(commit=False)
        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']

        if commit:
            user.save()
            return user
Exemple #4
0
class AuthenticationForm(forms.Form):
    required_css_class = 'required'
    email = forms.EmailField(
        label=_("E-mail"), widget=forms.EmailInput(attrs={'autofocus': True}))
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}),
    )

    error_messages = {
        'incomplete':
        _('You need to fill out all fields.'),
        'invalid_login':
        _("We have not found an account with this email address and password."
          ),
        'inactive':
        _("This account is disabled."),
        'unverified':
        _("You have not yet activated your account and set a password. Please click the link in the "
          "email we sent you. Click \"Reset password\" to receive a new email in case you cannot find "
          "it again."),
    }

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.customer_cache = None
        super().__init__(*args, **kwargs)

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

        if email is not None and password:
            try:
                u = self.request.organizer.customers.get(email=email.lower())
            except Customer.DoesNotExist:
                # Run the default password hasher once to reduce the timing
                # difference between an existing and a nonexistent user (django #20760).
                Customer().set_password(password)
            else:
                if u.check_password(password):
                    self.customer_cache = u
            if self.customer_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                )
            else:
                self.confirm_login_allowed(self.customer_cache)
        else:
            raise forms.ValidationError(self.error_messages['incomplete'],
                                        code='incomplete')

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )
        if not user.is_verified:
            raise forms.ValidationError(
                self.error_messages['unverified'],
                code='unverified',
            )

    def get_customer(self):
        return self.customer_cache
Exemple #5
0
class SignUpForm(UserCreationForm):
    email = forms.EmailField(help_text='must be unique',
                             required=True,
                             widget=forms.EmailInput(
                                 attrs={
                                     'placeholder': 'E-Mail',
                                     'class': 'form-control',
                                     'style': 'width:200px'
                                 }))
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Password',
            'class': 'form-control',
            'style': 'width:200px'
        }),
                                label="Password",
                                required=True)
    password2 = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Confirm Password',
            'class': 'form-control',
            'style': 'width:200px'
        }),
                                label="Confirm Password",
                                required=True)
    username = forms.CharField(widget=forms.TextInput(
        attrs={
            'placeholder': 'Username',
            'class': 'form-control',
            'style': 'width:200px'
        }),
                               label="Username",
                               required=True)
    first_name = forms.CharField(required=True,
                                 widget=forms.TextInput(
                                     attrs={
                                         'placeholder': 'First Name',
                                         'class': 'form-control',
                                         'style': 'width:200px'
                                     }))
    last_name = forms.CharField(required=False,
                                widget=forms.TextInput(
                                    attrs={
                                        'placeholder': 'Last Name',
                                        'class': 'form-control',
                                        'style': 'width:200px'
                                    }))

    def clean_email(self):
        mail = self.cleaned_data['email']
        try:
            match = User.objects.get(email__iexact=mail)
        except:
            return mail
        raise forms.ValidationError("Email already exists.")

    class Meta:
        model = User
        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2',
        )
Exemple #6
0
class RegisterForm(forms.Form):
    username = forms.EmailField(validators=[EmailValidator], widget=forms.EmailInput(attrs={'placeholder': 'Email'}), label='')
    password = forms.CharField(validators=[check_password], widget=forms.PasswordInput(attrs={'placeholder': 'Hasło'}), label='')
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Powtórz hasło'}), label='')
Exemple #7
0
class RegForm(forms.Form):
    username = forms.CharField(
        label='用户名',
        max_length=30,
        min_length=3,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入3-30位用户名'
        }))
    email = forms.EmailField(label='邮箱',
                             widget=forms.EmailInput(attrs={
                                 'class': 'form-control',
                                 'placeholder': '请输入邮箱'
                             }))
    password = forms.CharField(
        label='密码',
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入密码'
        }))
    password_again = forms.CharField(
        label='再输入一次密码',
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '再输入一次密码'
        }))
    verification_code = forms.CharField(
        label='验证码',
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '点击“发送验证码”发送到邮箱'
        }))

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(RegForm, self).__init__(*args, **kwargs)

    def clean(self):
        # 判断验证码
        code = self.request.session.get('register_code', '')
        verification_code = self.cleaned_data.get('verification_code', '')
        if not (code != '' and code == verification_code):
            raise forms.ValidationError('验证码不正确')
        return self.cleaned_data

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已存在')
        return email

    def clean_password_again(self):
        password = self.cleaned_data['password']
        password_again = self.cleaned_data['password_again']
        if password != password_again:
            raise forms.ValidationError('两次输入的密码不一致')
        return password_again

    def clean_verification_code(self):
        verification_code = self.cleaned_data.get('verification_code',
                                                  '').strip()
        if verification_code == '':
            raise forms.ValidationError('验证码不能为空')
        return verification_code
Exemple #8
0
class CustomPasswordResetForm(PasswordResetForm):
    email = forms.EmailField(
        label=_("Email"),
        max_length=254,
        widget=forms.EmailInput(attrs={'autocomplete': 'email'}))
Exemple #9
0
class RegisterForm(forms.Form):
    """ form register. """

    # Atributos > input en nuestro formulario
    username = forms.CharField(
        required=True,
        min_length=4,
        max_length=50,
        # Agregando estilos # attrs diccionario para class, id, placeholder
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'id': 'username',
            'placeholder': 'Username'
        }))

    email = forms.EmailField(required=True,
                             widget=forms.EmailInput(
                                 attrs={
                                     'class': 'form-control',
                                     'id': 'email',
                                     'placeholder': '*****@*****.**'
                                 }))

    password = forms.CharField(
        required=True,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
        }))

    # Verificacion del password
    password2 = forms.CharField(
        label='Verification Password',
        required=True,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}))

    #prefijo clean_username
    def clean_username(self):

        # username = campo que queremos validar
        username = self.cleaned_data.get('username')

        # saber si existe o no un usuaario
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('El usuario ya se encuentra en uso')
        return username

    def clean_email(self):

        # username = campo que queremos validar
        email = self.cleaned_data.get('email')

        # saber si existe o no un usuaario
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('Este correo ya se encuentra en uso')
        return email

    # Sobreescribiendo el metodo clean(usar cuando dependa un atributo de otro)
    def clean(self):
        cleaned_data = super().clean()

        if cleaned_data.get('password2') != cleaned_data.get('password'):
            self.add_error('password2', 'El password no coincide')

    def save(self):
        return User.objects.create_user(
            self.cleaned_data.get('username'),
            self.cleaned_data.get('email'),
            self.cleaned_data.get('password'),
        )
Exemple #10
0
class CustomUserCreationFormPatient(UserCreationForm):
    dob = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={'class': 'form-control datepicker'}))
    username = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'autocomplete': 'off'
                               }))
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'class': 'form-control'}))
    first_name = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'autocomplete': 'off'
        }))
    last_name = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'autocomplete': 'off'
                                }))
    phone = forms.CharField(max_length=30,
                            widget=forms.TextInput(attrs={
                                'class': 'form-control',
                                'autocomplete': 'off'
                            }))
    sex = forms.ChoiceField(
        choices=GENDER_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control'}))
    blood_group = forms.ChoiceField(
        choices=BLOOD_GROUPS,
        widget=forms.Select(attrs={'class': 'form-control'}))
    password1 = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'type': 'password',
                                }))
    password2 = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'type': 'password',
                                }))

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('first_name', 'last_name', 'email', 'username', 'phone')

    def __init__(self, *args, **kwargs):
        super(CustomUserCreationFormPatient, self).__init__(*args, **kwargs)
        self.fields['email'].label = "Email Address"
        self.fields['password1'].label = "Password"
        self.fields['password2'].label = "Re-Type Password"
        self.fields['dob'].label = "Date of Birth"

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_patient = True

        user.save()

        patient = Patient.objects.create(user=user)
        return patient
Exemple #11
0
class CustomUserCreationFormDoctor(UserCreationForm):
    dob = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={
            'class': 'form-control datepicker',
            'autocomplete': 'off'
        }))
    departmentname = forms.ModelChoiceField(
        queryset=Department.objects.all(),
        to_field_name="departmentname",
        widget=forms.Select(attrs={'class': 'form-control'}))
    username = forms.CharField(max_length=30,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'autocomplete': 'off'
                               }))
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'class': 'form-control'}))
    first_name = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'autocomplete': 'off'
        }))
    last_name = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'autocomplete': 'off'
                                }))
    phone = forms.CharField(max_length=30,
                            widget=forms.TextInput(attrs={
                                'class': 'form-control',
                                'autocomplete': 'off'
                            }))
    password1 = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'type': 'password',
                                }))
    password2 = forms.CharField(max_length=30,
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control',
                                    'type': 'password',
                                }))

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('first_name', 'last_name', 'email', 'username', 'phone')

    def __init__(self, *args, **kwargs):
        super(CustomUserCreationFormDoctor, self).__init__(*args, **kwargs)
        self.fields['email'].label = "Email Address"
        self.fields['password1'].label = "Password"
        self.fields['password2'].label = "Re-Type Password"
        self.fields['dob'].label = "Date of Birth"

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_doctor = True

        user.save()

        # user.role.set(range(Role.DOCTOR))
        doctor = Doctor.objects.create(user=user)
        Employee.objects.create(user=user)
        # doctor.departmentname.add(*self.get('departmentname'))
        # doctor.usericon.add(*self.get('usericon'))

        return doctor
Exemple #12
0
 def __init__(self, *args, **kwargs):
     super(contactRecordForms,self).__init__(*args, **kwargs)
     self.fields['dob'].widget = forms.DateInput(attrs = { 'type' : 'date'})
     self.fields['dob'].label = 'Date of Birth'
     self.fields['email'].widget = forms.EmailInput(attrs={ 'type' : 'email'})
Exemple #13
0
class EditStudents(forms.Form):
    required_css_class = 'required'
    # 会给编辑账号人员显示客户唯一ID(数据库的唯一ID),但是这个ID为只读'readonly': True
    id = forms.CharField(label='学员唯一ID',
                         widget=forms.TextInput(attrs={
                             "class": "form-control",
                             'readonly': True
                         }))
    name = forms.CharField(
        max_length=50,
        min_length=2,
        label='学员姓名',
        required=True,
        widget=forms.TextInput(attrs={"class": "form-control"}))
    phone_regex = RegexValidator(regex=r'^1\d{10}$',
                                 message="手机号码需要使用11位数字, 例如:'13911153335'")
    phone_number = forms.CharField(
        validators=[phone_regex],
        min_length=11,
        max_length=11,
        label='手机号码',
        required=True,
        widget=forms.NumberInput(attrs={"class": "form-control"}))
    qq_regex = RegexValidator(regex=r'^\d{5,20}$',
                              message="QQ号码需要使用5到20位数字, 例如:'605658506'")
    qq_number = forms.CharField(
        validators=[qq_regex],
        min_length=5,
        max_length=20,
        label='QQ号码',
        required=True,
        widget=forms.NumberInput(attrs={"class": "form-control"}))
    mail = forms.EmailField(
        required=False,
        label='Email地址',
        error_messages={'invalid': '请输入正确格式的电子邮件地址'},
        widget=forms.EmailInput(attrs={"class": "form-control"}))
    direction_choices = (('安全', '安全'), ('教主VIP', '教主VIP'))
    direction = forms.CharField(max_length=10,
                                label='学习方向',
                                widget=forms.Select(
                                    choices=direction_choices,
                                    attrs={"class": "form-control"}))
    class_adviser_choices = (('小雪', '小雪'), ('菲儿', '菲儿'))
    class_adviser = forms.CharField(max_length=10,
                                    label='班主任',
                                    widget=forms.Select(
                                        choices=class_adviser_choices,
                                        attrs={"class": "form-control"}))
    payed_choices = (('已缴费', '已缴费'), ('未交费', '未交费'))
    payed = forms.CharField(max_length=10,
                            label='缴费情况',
                            widget=forms.Select(
                                choices=payed_choices,
                                attrs={"class": "form-control"}))

    def clean_phone_number(self):
        phone_number = self.cleaned_data['phone_number']
        # 在编辑的时候,校验电话号码与创建不同,因为其实数据库里边已经有一个自己这个条目的电话号码了!
        # 所以要排除自己ID查到的电话号码,如果其他ID依然存在相同的电话号码,就校验失败
        count = 0
        for i in StudentsDB.objects.filter(phone_number=phone_number):
            if int(i.id) != int(self.cleaned_data['id']):
                count += 1

        if count >= 1:
            raise forms.ValidationError("电话号码已经存在")
        return phone_number

    def clean_qq_number(self):
        qq_number = self.cleaned_data['qq_number']

        count = 0
        for i in StudentsDB.objects.filter(qq_number=qq_number):
            if int(i.id) != int(self.cleaned_data['id']):
                count += 1

        if count >= 1:
            raise forms.ValidationError("QQ号码已经存在")
        return qq_number
Exemple #14
0
class StudentsForm(forms.Form):
    # 为了添加必选项前面的星号
    # 下面是模板内的内容
    """
    < style type = "text/css" >
    label.required::before
    {
        content: "*";
    color: red;
    }
    < / style >
    """
    required_css_class = 'required'  # 这是Form.required_css_class属性, use to add class attributes to required rows
    # 添加效果如下
    # <label class="required" for="id_name">学员姓名:</label>
    # 不添加效果如下
    # <label for="id_name">学员姓名:</label>

    # 学员姓名,最小长度2,最大长度10,
    # label后面填写的内容,在表单中显示为名字,
    # 必选(required=True其实是默认值)
    # attrs={"class": "form-control"} 主要作用是style it in Bootstrap
    name = forms.CharField(
        max_length=10,
        min_length=2,
        label='学员姓名',
        required=True,
        widget=forms.TextInput(attrs={"class": "form-control"}))
    # 对电话号码进行校验,校验以1开头的11位数字
    phone_regex = RegexValidator(regex=r'^1\d{10}$',
                                 message="手机号码需要使用11位数字, 例如:'13911153335'")
    phone_number = forms.CharField(
        validators=[phone_regex],
        min_length=11,
        max_length=11,
        label='手机号码',
        required=True,
        widget=forms.NumberInput(attrs={"class": "form-control"}))
    qq_regex = RegexValidator(regex=r'^\d{5,20}$',
                              message="QQ号码需要使用5到20位数字, 例如:'605658506'")
    qq_number = forms.CharField(
        validators=[qq_regex],
        min_length=5,
        max_length=20,
        label='QQ号码',
        required=True,
        widget=forms.NumberInput(attrs={"class": "form-control"}))
    mail = forms.EmailField(
        required=False,
        label='Email地址',
        error_messages={'invalid': '请输入正确格式的电子邮件地址'},
        widget=forms.EmailInput(attrs={"class": "form-control"}))
    direction_choices = (('安全', '安全'), ('教主VIP', '教主VIP'))
    direction = forms.CharField(max_length=10,
                                label='学习方向',
                                widget=forms.Select(
                                    choices=direction_choices,
                                    attrs={"class": "form-control"}))
    class_adviser_choices = (('小雪', '小雪'), ('菲儿', '菲儿'))
    class_adviser = forms.CharField(max_length=10,
                                    label='班主任',
                                    widget=forms.Select(
                                        choices=class_adviser_choices,
                                        attrs={"class": "form-control"}))
    payed_choices = (('已缴费', '已缴费'), ('未交费', '未交费'))
    payed = forms.CharField(max_length=10,
                            label='缴费情况',
                            widget=forms.Select(
                                choices=payed_choices,
                                attrs={"class": "form-control"}))

    def clean_phone_number(self):  # 对电话号码的唯一性进行校验,注意格式为clean+校验变量
        phone_number = self.cleaned_data['phone_number']  # 提取客户输入的电话号码
        # 在数据库中查找是否存在这个电话号
        existing = StudentsDB.objects.filter(
            phone_number=phone_number).exists()
        # 如果存在就显示校验错误信息
        if existing:
            raise forms.ValidationError("电话号码已经存在")
        # 如果校验成功就返回电话号码
        return phone_number

    def clean_qq_number(self):
        qq_number = self.cleaned_data['qq_number']
        existing = StudentsDB.objects.filter(qq_number=qq_number).exists()

        if existing:
            raise forms.ValidationError("QQ号码已经存在")
        return qq_number
class AppRegForm(forms.Form):
    password = forms.CharField(
        label=u'密码',
        help_text=u'',
        min_length=6,
        max_length=8,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
    )

    confirm_password = forms.CharField(
        label=u'密码',
        help_text=u'',
        min_length=6,
        max_length=8,
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
    )

    email = forms.EmailField(
        label=u'邮箱',
        help_text=u'请输入有效的邮箱,请把[email protected]的邮箱设置白名单',
        max_length=60,
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
    )

    phone = forms.CharField(
        label=u'手机号码',
        help_text=u'请输入有效的手机号,以便接收短信验证',
        max_length=11,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
    )

    captcha = forms.CharField(
        label=u'验证码',
        min_length=6,
        max_length=6,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(AppRegForm, self).__init__(*args, **kwargs)
        self.fields['captcha'].initial = ''

    def get_captcha(self):
        code = self.data['captcha']
        if not code or len(code) != 6:
            raise forms.ValidationError(u'验证码错误')
        return code

    def save(self):
        email = self.cleaned_data['email']
        phone = self.cleaned_data['phone']
        password = self.cleaned_data['password']
        uname = uuid.uuid4().hex

        ipobj, ok = IpAddress.objects.get_or_create(
            ipaddr=self.request.META.get('REMOTE_ADDR'))
        #         try:
        obj = AppUser.objects.create(email=email,
                                     phone=phone,
                                     key=make_password(password),
                                     uuid=uname,
                                     uname=uname[:6],
                                     regtime=timezone.now(),
                                     regip=ipobj,
                                     data={})
Exemple #16
0
class RegistrationForm(forms.Form):
    login = forms.CharField(
        min_length=3,
        max_length=20,
        label='Login',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'SuperPupkin'
        }))

    email = forms.CharField(
        min_length=3,
        max_length=255,
        label='Email',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '*****@*****.**'
        }))
    name = forms.CharField(min_length=3,
                           max_length=20,
                           label='Name',
                           widget=forms.TextInput(attrs={
                               'class': 'form-control',
                               'placeholder': 'Pupkin'
                           }))
    password = forms.CharField(
        min_length=4,
        max_length=20,
        label='Password',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '***********'
        }))
    password_repeat = forms.CharField(
        min_length=4,
        max_length=20,
        label='Repeat password',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '***********'
        }))

    avatar = forms.FileField(label='Avatar', required=False)

    def clean_login(self):
        username = self.cleaned_data['login']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('User with this login exist!')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('User with this email exist!')
        return email

    def clean_password_repeat(self):
        password_repeat = self.cleaned_data['password_repeat']
        if self.cleaned_data['password'] != password_repeat:
            raise forms.ValidationError('Passwords are not equal.')
        return password_repeat

    '''
    def clean_avatar(self):
        avatar = self.cleaned_data['avatar']
        if avatar is not None and 'avatar' not in avatar.content_type:
            raise forms.ValidationError(u'Format file is bad!')
        return avatar
    '''

    def clean(self):
        # Create user
        # If exist -> Exception
        pass

    def save(self):
        user = User.objects.create_user(self.cleaned_data['login'],
                                        self.cleaned_data['email'],
                                        self.cleaned_data['password'])
        if self.cleaned_data['avatar'] is None:
            print('WARNING -avatar is None')
            return Profile.objects.create(user=user)
        return Profile.objects.create(user=user,
                                      avatar=self.cleaned_data['avatar'])
Exemple #17
0
class Emp_insert_Form(forms.Form):
    emp_id = forms.IntegerField(
        label="Enter Your Id",
        widget=forms.NumberInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Enter Your Id"
            }
        )
    )
    emp_first_name=forms.CharField(
        label="Enter First Name",
        widget=forms.TextInput(
            attrs={
                'class':'form-control',
                'placeholder':"First Name"
            }
        )
    )
    emp_last_name = forms.CharField(
        label="Enter Last Name",
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Last Name"
            }
        )
    )
    emp_mobile_number = forms.IntegerField(
        label="Enter Mobile Number",
        widget=forms.NumberInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Your Mobile Number"
            }
        )
    )
    emp_email_id = forms.EmailField(
        label="Enter Email Id",
        widget=forms.EmailInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Your Email Id"
            }
        )
    )
    emp_salary = forms.IntegerField(
        label="Enter Your Salary",
        widget=forms.NumberInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Your Salary"
            }
        )
    )
    emp_location = forms.CharField(
        label="Enter Your Location",
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': "Your location"
            }
        )
    )
    emp_position=forms.CharField(
        label="Enter Your Position",
        widget=forms.TextInput(
            attrs={
                'class':'form-control',
                'placeholder':"Your Position"
            }
        )
    )
Exemple #18
0
 class Meta:
     model = User
     fields = ('username', 'email', 'password', 'phone', 'user_group',
               'is_active', 'is_staff')
     widgets = {
         'username':
         forms.TextInput(attrs={
             'class': 'form-control',
             'placeholder': 'username'
         }),
         'email':
         forms.EmailInput(attrs={
             'class': ' form-control',
             'placeholder': 'email'
         }),
         'password':
         forms.PasswordInput(attrs={
             'class': 'form-control',
             'placeholder': 'password'
         }),
         'phone':
         forms.TextInput(attrs={
             'class': 'form-control',
             'placeholder': 'phone'
         }),
         'user_group':
         forms.Select(
             attrs={
                 'class': 'form-control select2',
                 'multiple': 'multiple',
                 'data-placeholder': 'user group'
             }),
         'is_active':
         forms.Select(choices=((True, '是'), (False, '否')),
                      attrs={
                          'class': 'form-control',
                          'placeholder': 'is_active'
                      }),
         'is_staff':
         forms.Select(choices=((True, '是'), (False, '否')),
                      attrs={
                          'class': 'form-control select2',
                          'placeholder': 'is_staff'
                      })
     }
     labels = {
         'username': '******',
         'email': '邮箱',
         'password': '******',
         'phone': '电话',
         'user_group': '用户组',
         'is_active': '是否激活',
         'is_staff': '是否为管理员',
     }
     error_messages = {
         'username': {
             'required': u'请输入用户名',
             'max_length': u'用户名过长',
         },
         'email': {
             'required': u'请输入邮箱',
             'max_length': u'邮箱地址过长',
         },
         'password': {
             'required': u'请输入密码',
             'max_length': u'密码过长',
             'invalid': u'请输入有效邮箱'
         }
     }
Exemple #19
0
class LoginForm(forms.Form):
    username = forms.CharField(validators=[EmailValidator], widget=forms.EmailInput(attrs={'placeholder': 'Email'}), label='')
    password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Hasło'}), label='')
Exemple #20
0
class ForgotPasswordForm(forms.Form):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入用户名'
        }))
    email = forms.EmailField(
        label='注册邮箱',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入用户绑定的邮箱'
        }))
    new_password = forms.CharField(
        label='新密码',
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入新密码'
        }))
    new_password_again = forms.CharField(
        label='确认密码',
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '再次输入新密码'
        }))
    verification_code = forms.CharField(
        label='验证码',
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '点击获取验证码,注意查看邮箱'
        }))

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(ForgotPasswordForm, self).__init__(*args, **kwargs)

    def clean(self):
        new_password = self.cleaned_data.get('new_password', '')
        new_password_again = self.cleaned_data.get('new_password_again', '')
        if not (new_password != new_password_again or new_password != ''):
            raise forms.ValidationError('两次输入的密码不一致!')
        return self.cleaned_data

    def clean_username(self):
        username = self.cleaned_data['username'].strip()
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名不存在!')
        return username

    def clean_email(self):
        email = self.cleaned_data['email'].strip()
        if not User.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱不存在!')
        return email

    def clean_verification_code(self):
        verification_code = self.cleaned_data.get('verification_code',
                                                  '').strip()
        if verification_code == '':
            raise forms.ValidationError('验证码不能为空')
        code = self.request.session.get('forgot_password_code', '')
        # 获取用户输入的验证码
        # 如果发送的验证码没有过期,并且用户输入的验证码与发送的验证码不一致,报错
        if not (code != '' and code == verification_code):
            raise forms.ValidationError('验证码不正确')
        return verification_code
Exemple #21
0
class PasswordResetForm(forms.Form):
    email = forms.CharField(label='email', max_length=100, widget=forms.EmailInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['email'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Email'})
Exemple #22
0
class SignUpForm(UserCreationForm):
    class Meta:
        model = UserModel
        fields = (
            "username",
            "email",
            "password1",
            "password2",
        )

    username = forms.CharField(
        label=_("Username"),
        max_length=50,
        required=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, " "digits and @/./+/-/_ only."
        ),
        widget=forms.TextInput(
            attrs={"class": "form-control", "placeholder": "Username"}
        ),
    )
    email = forms.EmailField(
        label=_("Email"),
        max_length=255,
        required=True,
        help_text=_(
            "Required. Type a valid email address. Used for password " "recovery."
        ),
        widget=forms.EmailInput(
            attrs={"placeholder": "*****@*****.**", "class": "form-control"}
        ),
    )
    password1 = forms.CharField(
        label=_("Password:"******"<ul><li>Your password can't be too similar "
            "to your other personal information </li>"
            "<li>Your password must contain at least 8 characters.</li>"
            "<li>Your password can't be a commonly used password.</li>"
            "<li>Your password can't be entirely numeric.</li></ul>"
        ),
        widget=forms.PasswordInput(
            attrs={"class": "form-control", "placeholder": "Password"}
        ),
    )
    password2 = forms.CharField(
        label=_("Password confirmation:"),
        max_length=50,
        required=True,
        help_text=_("Enter the same password as before, for verification."),
        widget=forms.PasswordInput(
            attrs={"class": "form-control", "placeholder": "Confirm password"}
        ),
    )

    error_messages = {
        "unique_email": _("Email already in use."),
        "password_mismatch": _("Passwords do not match."),
    }

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()

        email = cleaned_data.get("email", "").lower()

        num_users = UserModel.objects.filter(email=email).count()
        if num_users > 0:
            self.add_error("email", self.error_messages["unique_email"])
Exemple #23
0
class CalibrationForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'placeholder': 'First Name'
        }
    ))

    last_name = forms.CharField(widget = forms.TextInput(
        attrs={
            'class': 'form-control',
            'placeholder': 'Last Name'
        }
    ))


    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female')
    )

    gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.Select(
        attrs={
            'class':'form-control',
            'placeholder':'Select'
        }
    ))

    STATE_CHOICE = (
        ('ABIA', 'ABIA'),
        ('ADAMAWA', 'ADAMAWA'),
        ('AKWA IBOM', 'AKWA IBOM'),
        ('KANO', 'KANO')
    )

    state= forms.ChoiceField(choices=STATE_CHOICE, widget=forms.Select( 
        attrs = {
            'class':'form-control'
        }
    ))

    phone = forms.IntegerField(widget=forms.NumberInput( 
        attrs={
            'class':'form-control',
            'placeholder':'Phone Number'
        }
    ))

    email = forms.EmailField(widget =forms.EmailInput( 
        attrs={
            'class': 'form-control',
            'placeholder': 'Email'
        }
    ))

    tyre_make = forms.CharField(widget=forms.TextInput(
        attrs={
            'class':'form-control',
            'placeholder':'Tyre Make'
        }
    ))

    tyre_guage = forms.IntegerField(widget = forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Tyre Guage'
        }
    ))
 

    VALVE_POSITION_CHOICES = (
        ('OPEN', 'OPEN'),
        ('CLOSE', 'CLOSE'),
        ('NONE', 'NONE')
    )

    valve_position = forms.ChoiceField(choices=VALVE_POSITION_CHOICES, widget=forms.Select(
        attrs={
            'class':'form-control',
            'placeholder':'Valve Position'
        }
    ))

    job_number = forms.IntegerField(widget = forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Job Number'
        }
    ))



    TANK_POSITION_CHOICES = (
        ('BALLON', 'BALLON'),
        ('SPRING', 'SPRING')
    )

    tank_position = forms.ChoiceField(choices=TANK_POSITION_CHOICES , widget = forms.Select(
        attrs={
            'class':'form-control',
            'placeholder':'Tank Position'
        }
    ))

    registration_number = forms.CharField(widget=forms.TextInput(
        attrs={
            'class':'form-control',
            'placeholder':'Registration Number'
        }
    ))

    transporter = forms.CharField(widget=forms.TextInput(
        attrs={
            'class':'form-control',
            'placeholder':'Transporter'
        }
    ))

    chasis_number = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Chasis Number'
        }
    ))
    
    date_issued = forms.CharField(widget=forms.DateInput(
        attrs={
            'class':'form-control',
            'placeholder':'yyyy-mm-dd'
        }
    ))

    date_expired = forms.CharField(widget=forms.DateInput(
        attrs={
            'class':'form-control',
            'placeholder':'yyyy-mm-dd'
        }
    ))

    certificate_number = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Certificate Number'
        }
    ))

    capacity = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class':'form-control',
            'placeholder':'Capacity'
        }
    ))

    document = forms.FileField(widget=forms.FileInput(
        attrs={
            'class':'form-control'
        }
    ))
     

    class Meta:
        model = Calibration
        fields = ('first_name', 'last_name','gender','state','phone','email',
                'tyre_make','tyre_guage','valve_position','job_number','tank_position',
                'registration_number','transporter','chasis_number','date_issued','date_expired',
                'certificate_number','capacity','document')
Exemple #24
0
class NewsletterSignupForm(forms.Form):
    """A form for adding an email to a MailChimp mailing list."""
    email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'email address'}))
    list = forms.CharField(widget=forms.HiddenInput)
    default = forms.BooleanField(initial=True, required=False)
Exemple #25
0
    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)

        self.fields['name'] = forms.CharField(
            max_length=225,
            required=True,
            widget=forms.TextInput(
                attrs={
                    'type': 'text',
                    'name': 'name',
                    'class': 'form-control',
                    'id': 'Name',
                    'placeholder': 'Enter Name',
                    'onblur': ''
                }))

        self.fields['email'] = forms.EmailField(
            max_length=50,
            required=True,
            widget=forms.EmailInput(
                attrs={
                    'type': 'email',
                    'name': 'email',
                    'class': 'form-control',
                    'id': 'Email',
                    'placeholder': 'Enter Email'
                }))

        self.fields['contact'] = forms.CharField(
            required=True,
            widget=forms.TextInput(
                attrs={
                    'type': 'text',
                    'name': 'contact',
                    'class': 'form-control',
                    'id': 'Contact',
                    'placeholder': 'Enter Contact No.',
                    'onblur': ''
                }))
        self.fields['student_number'] = forms.CharField(
            required=True,
            widget=forms.TextInput(
                attrs={
                    'type': 'text',
                    'class': 'form-control',
                    'id': 'Student',
                    'placeholder': 'Enter Student Number',
                    'onblur': ''
                }))

        self.fields['branch'] = forms.ModelChoiceField(
            queryset=Branch.objects.filter(active=True),
            required=True,
            widget=forms.Select(
                # choices=BRANCH_CHOICES,
                attrs={
                    'class': 'form-control',
                    'data-val': 'true',
                    'data-val-required': '*',
                    'id': 'Branch',
                    'name': 'Branch',
                    'onchange': 'validateBranch()'
                }))

        self.fields['year'] = forms.ModelChoiceField(
            queryset=Year.objects.filter(active=True),
            required=True,
            widget=forms.Select(attrs={
                'class': 'form-control',
                'data-val': 'true',
                'data-val-required': '*',
                'id': 'Year',
                'name': 'Year'
            }, ),
        )

        self.fields['gender'] = forms.ModelChoiceField(
            queryset=Gender.objects.all(),
            required=True,
            widget=forms.Select(
                attrs={
                    'class': 'form-control',
                    'data-val': 'true',
                    'data-val-required': '*',
                    'id': 'Gender',
                    'name': 'Gender',
                    'type': 'radio'
                }))

        self.fields['hosteler'] = forms.BooleanField(
            required=False,
            widget=forms.CheckboxInput(
                attrs={
                    'data-val': 'true',
                    'data-val-required': 'the hosteler field is required',
                    'id': 'IsHosteler',
                    'name': 'IsHosteler',
                    'type': 'checkbox'
                }))
Exemple #26
0
class PwdResetForm(forms.Form):
    username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label="邮箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'}))
    captcha = CaptchaField(label='验证码')
Exemple #27
0
class AppointmentForm(ErrorClassMixin, forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'Имя'
    }),
                           label='Имя')
    email = forms.CharField(widget=forms.EmailInput(attrs={
        'class': 'form-control',
        'placeholder': 'Email'
    }),
                            label='Email')
    phone_number = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Номер телефона'
        }),
        label='Номер телефона')
    clinic = MyChoiceField(widget=forms.Select(attrs={'class': 'form-select'}),
                           label='Клиника')
    date = MyChoiceField(widget=forms.Select(attrs={'class': 'form-select'}),
                         label='Дата')
    time = MyChoiceField(widget=forms.Select(attrs={'class': 'form-select'}),
                         label='Время')
    description = forms.CharField(widget=forms.Textarea(
        attrs={
            'class': 'form-control',
            'style': 'height: 100px',
            'placeholder': 'Описание'
        }),
                                  label='Краткое изложение проблемы')

    def save(self):
        clinic = Clinic.objects.get(name=self.cleaned_data['clinic'])
        try:
            patient = Patient.objects.get(
                name=self.cleaned_data['name'],
                email=self.cleaned_data['email'],
                phone_number=self.cleaned_data['phone_number'])
        except Patient.DoesNotExist:
            patient, _ = Patient.objects.update_or_create(
                email=self.cleaned_data['email'],
                defaults={
                    'phone_number': self.cleaned_data['phone_number'],
                    'name': self.cleaned_data['name']
                })
        appointment = Appointment.objects.filter(
            clinic=clinic,
            date=self.cleaned_data['date'],
            time=self.cleaned_data['time']).update(
                patient=patient, problem=self.cleaned_data['description'])
        return appointment

    def clean_phone_number(self):
        phone_number = self.cleaned_data['phone_number']
        if not re.match(r'^\+[\d]{11}$', phone_number):
            raise forms.ValidationError(
                'Телефон должен быть записан в формате +7XXXXXXXXXX.')
        return phone_number

    def clean_email(self):
        email = self.cleaned_data['email']
        if not re.match(r'^\S+@\S+\.\S+$', email):
            raise forms.ValidationError(
                'Введите корректный электронный адрес.')
        return email
Exemple #28
0
 class Meta:
     exclude = ['marital_status']
     widgets = {
         'email':
         forms.EmailInput(attrs={'placeholder': 'University Email'}),
     }
Exemple #29
0
class UserUpForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control',
            'type': "text",
            'name': "first_name",
            'placeholder': _('სახელი'),
        }),
                                 label=_('სახელი'),
                                 required=True)
    last_name = forms.CharField(max_length=50,
                                widget=forms.TextInput(
                                    attrs={
                                        'class': 'form-control',
                                        'type': "text",
                                        'name': "last_name",
                                        'placeholder': _('გვარი'),
                                    }),
                                label=_('გვარი'),
                                required=True)
    email = forms.CharField(max_length=50,
                            widget=forms.EmailInput(
                                attrs={
                                    'class': 'form-control',
                                    'type': "email",
                                    'name': "email",
                                    'placeholder': _('ემაილი'),
                                }),
                            label=_('ემაილი'),
                            required=True)
    phone = forms.CharField(widget=forms.NumberInput(attrs={
        'class': 'form-control',
        'name': 'phone',
    }),
                            label=_("მობ.ტელეფონი"),
                            required=True)
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'class': 'form-control',
            'type': "password",
            'name': "password",
            'placeholder': _('პაროლი'),
        }),
                               label=_('პაროლი'),
                               required=True)
    confpassword = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'type': "password",
            'name': "confpassword",
        }),
        label=_('გაიმეორეთ პაროლი'),
        required=True)
    rules = forms.BooleanField(widget=forms.CheckboxInput(attrs={
        'type': 'checkbox',
        'name': 'rules',
    }),
                               label=_('წესები'),
                               required=True)
    personal_number = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class': 'form-control',
            'placeholder': _('პირადი ნომერი'),
            'name': 'personal_number',
        }),
                                         label=_("პირადი ნომერი"),
                                         required=True)
    sex = forms.ChoiceField(
        widget=forms.Select(attrs={
            'id': 'sex',
            'class': 'dropdown-select form-control'
        }),
        label=_('სქესი'),
        choices=Account.ASC)

    def clean_confpassword(self):
        # cleaned_data = super(UserUpForm, self).clean()
        password = self.cleaned_data['password']
        password1 = self.cleaned_data['confpassword']
        if password != password1:
            raise forms.ValidationError(
                _('პაროლის დადასტურება არ ემთხვევა პაროლს'))
        return password

    class Meta:
        model = Account
        fields = [
            'first_name', 'last_name', 'email', 'phone', 'personal_number',
            'password', 'confpassword', 'sex', 'rules'
        ]
class SignUpForm(forms.ModelForm):
    """
    A form for creating new users.
    """
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=30, required=True, label=_('Username'),
        help_text=_("Username may contain alphanumeric, '_' and '.' characters."))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label=_('Password'), required=True)
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label=_('Confirm your password'), required=True)
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': 'form-control'}),
        required=True, max_length=75, label=_('Email'))

    class Meta:
        model = User
        exclude = ['last_login', 'date_joined']
        fields = ['username', 'email', 'password', 'confirm_password',]

    def __init__(self, *args, **kwargs):
        """
        验证表单数据合法性
        """
        super(SignUpForm, self).__init__(*args, **kwargs)
        self.fields['username'].validators += [
            forbidden_username_validator, invalid_username_validator,
            unique_username_ignore_case_validator,
        ]
        self.fields['email'].validators += [
            unique_email_validator,
        ]

    def clean_password(self):
        '''
        验证两次输入密码是否一致
        '''
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and confirm_password and password != confirm_password:
            msg = _('Passwords don\'t match.')
            self.add_error('confirm_password', msg)
            
        return password
    
    def clean(self):
        self.clean_password()
        super(SignUpForm, self).clean()

    def save(self, commit=True):
        """
        保存前的操作
        """
        user = super().save(commit=False)
        self.clean()
        user.set_password(self.cleaned_data['password'])
        user.save()
        return user