Example #1
0
class LoginForm(forms.Form):
    userid = forms.CharField(label="学号",
                             min_length=8,
                             max_length=8,
                             widget=widgets.TextInput(attrs={
                                 "class": "form-control",
                                 "placeholder": "请输入学生id"
                             }),
                             error_messages={
                                 "min_length": "请输入8位学号",
                                 "max_length": "请输入8位学号",
                                 "required": "学号不能为空"
                             })
    email = forms.EmailField(label="邮箱",
                             widget=widgets.EmailInput(attrs={
                                 "class": "form-control",
                                 "placeholder": "请输入邮箱"
                             }),
                             error_messages={
                                 "required": "请输入正确的邮箱格式",
                                 "invalid": "请输入正确的邮箱格式"
                             })
    password = forms.CharField(
        label="密码",
        min_length=1,
        max_length=64,
        widget=widgets.PasswordInput(attrs={
            "class": "form-control",
            "placeholder": "请输入密码"
        }),
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码不能小于1个字符",
            "max_length": "密码不能大于64个字符"
        })

    captcha = CaptchaField(label="验证码",
                           widget=CaptchaTextInput(attrs={
                               "class": "form-control",
                               "placeholder": "验证码"
                           }))
Example #2
0
class UserForm(forms.Form):
    username = forms.CharField(
        label="用户名",
        max_length=128,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': "Username",
            'autofocus': ''
        }))
    password = forms.CharField(
        label="密码",
        max_length=256,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': "Password"
        }))
    captcha = CaptchaField(label='验证码',
                           widget=CaptchaTextInput(attrs={
                               'class': 'form-control',
                               'placeholder': "Captcha"
                           }))
Example #3
0
class CaptchaForm(forms.Form):
    """!
    Clase que contiene el campo de captcha a incorporar en un formulario

    @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
    @date 06-05-2016
    @version 2.0.0
    """

    ## Campo de validación de captcha
    captcha = CaptchaField(
        label=_("Captcha"),
        widget=CaptchaTextInput(
            attrs={
                'class': 'form-control input-sm',
                'placeholder': _("texto de la imagen"),
                'style': 'min-width: 0; width: auto; display: inline;',
                'data-toggle': 'tooltip',
                'title': _("Indique el texto de la imagen")
            }))
Example #4
0
class ForgetPasswordForm2(forms.Form):
    password1 = forms.CharField(
        label="请输入新密码",
        min_length=1,
        max_length=150,
        widget=widgets.PasswordInput(attrs={
            "class": "form-control",
            "placeholder": "请输入新密码"
        }),
        error_messages={
            "min_length": "密码不能小于1个字符",
            "max_length": "密码不能大于150个字符",
            "required": "密码不能为空"
        })
    password2 = forms.CharField(
        label="密码确认",
        min_length=1,
        max_length=150,
        widget=widgets.PasswordInput(attrs={
            "class": "form-control",
            "placeholder": "请再次输入密码"
        }),
        error_messages={
            "min_length": "密码不能小于1个字符",
            "max_length": "密码不能大于150个字符",
            "required": "密码不能为空"
        })
    captcha = CaptchaField(label="验证码",
                           widget=CaptchaTextInput(attrs={
                               "class": "form-control",
                               "placeholder": "验证码"
                           }))

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("两次密码不匹配, 请重新输入!")
        return password2
Example #5
0
class RegisterForm(forms.Form):
    gender = (
        ('male', '男'),
        ('female', '女'),
    )
    username = forms.CharField(label='用户名',
                               max_length=128,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'placeholder': '用户名'
                               }))
    password1 = forms.CharField(label='密码',
                                max_length=256,
                                widget=forms.PasswordInput(attrs={
                                    'class': 'form-control',
                                    'placeholder': '密码'
                                }))
    password2 = forms.CharField(
        label='确认密码',
        max_length=256,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '确认密码'
        }))
    email = forms.EmailField(label='邮箱地址',
                             widget=forms.EmailInput(attrs={
                                 'class': 'form-control',
                                 'placeholder': '邮箱地址'
                             }))
    sex = forms.ChoiceField(
        label='性别',
        choices=gender,
        initial='male',
        widget=forms.Select(attrs={'class': 'form-control'}))
    captcha = CaptchaField(label='验证码',
                           widget=CaptchaTextInput(attrs={
                               'class': 'form-control',
                               'placeholder': '请输入验证码'
                           }))
Example #6
0
    def __init__(self, *args, **kwargs):
        fields = (
            CharField(show_hidden_initial=True),
            CharField(),
        )
        if 'error_messages' not in kwargs or 'invalid' not in kwargs.get(
                'error_messages'):
            if 'error_messages' not in kwargs:
                kwargs['error_messages'] = {}
            kwargs['error_messages'].update({'invalid': _('Invalid CAPTCHA')})

        kwargs['widget'] = kwargs.pop(
            'widget',
            CaptchaTextInput(output_format=kwargs.pop('output_format', None),
                             id_prefix=kwargs.pop('id_prefix', None),
                             attrs={
                                 'class': 'captcha-input',
                                 'placeholder': _('Captcha Code')
                             }))
        self.hashKey = None

        super(CaptchaField, self).__init__(fields, *args, **kwargs)
Example #7
0
class LoginForm(forms.Form):
    name = forms.CharField(
        max_length=240,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '用户名',
            'autofocus': ''
        }))
    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class': 'form-control',
        'placeholder': '邮箱'
    }))
    password = forms.CharField(max_length=240,
                               widget=forms.PasswordInput(attrs={
                                   'class': 'form-control',
                                   'placeholder': '密码'
                               }))
    captcha = CaptchaField(
        label='验证码',
        required=True,
        error_messages={'required': '验证码不能为空'},
        widget=CaptchaTextInput(attrs={'class': 'form-control'}))
class ResetForm(forms.Form):
    password = forms.CharField(
        max_length=128,
        min_length=6,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '重置密码'
        }),
        error_messages={
            'max_length': '密码过长!',
            'min_length': '密码长度至少为6位!',
            'required': '请填写密码!'
        })
    captcha = CaptchaField(
        widget=CaptchaTextInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '请输入验证码'
        }),
        error_messages={
            'required': '请输入验证码!',
            'invalid': '验证码错误!'
        })
Example #9
0
class ContactForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.mark = kwargs.pop("mark", None)
        forms.Form.__init__(self, *args, **kwargs)
        #  Поле Name & sender становится недоступным для редактирования для аутентифицированных
        #  пользователей
        if self.mark:
            self.fields['name'].widget.attrs['readonly'] = True
            self.fields['sender'].widget.attrs['readonly'] = True

    attrs_dict = {'size': 40, "class": "form-control  border border-secondary"}

    name = forms.CharField(max_length=20,
                           help_text="Enter your name",
                           widget=forms.TextInput(attrs=attrs_dict))
    subject = forms.CharField(
        max_length=999,
        help_text="Enter  a subject of the message",
        widget=forms.TextInput(attrs=attrs_dict),
        validators=[
            MinLengthValidator(
                message=
                "Subject is way to short. Please do conjure up something meaningful",
                limit_value=10)
        ])
    sender = forms.EmailField(help_text="Enter your email address",
                              widget=forms.TextInput(attrs=attrs_dict))
    message = forms.CharField(help_text="please type in your message",
                              widget=forms.Textarea(attrs=attrs_dict))
    copy = forms.BooleanField(required=False, label="Send copy to your email")
    captcha = CaptchaField(
        help_text="Please type in correct captcha",
        widget=CaptchaTextInput(
            attrs={"style": "border-style: solid; border-color: #464451;"}),
        error_messages={
            'invalid':
            "Please type in correct captcha. I know it's not easy but please do concentrate on "
            "this task"
        })
Example #10
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)
    captcha = CaptchaField(
        label='验证码', widget=CaptchaTextInput(attrs={'class': 'form-control'}))
class LoginForm(forms.Form):
    username_or_email = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '用户名或邮箱'
        }),
        error_messages={'required': '请输入用户名或邮箱!'})
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '密码'
        }),
        error_messages={'required': '请输入密码!'})
    captcha = CaptchaField(
        widget=CaptchaTextInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '请输入验证码'
        }),
        error_messages={
            'required': '请输入验证码!',
            'invalid': '验证码错误!'
        })
Example #12
0
class ContactForm(forms.Form):
    your_name = forms.CharField(label='Your Name', max_length=100,
                                required=True,
                                widget=forms.TextInput(attrs={'class':'form-control'}))
    your_email = forms.EmailField(label='Your Email', max_length=100,
                                  required=True,
                                  widget=forms.TextInput(attrs={'class':'form-control'}))
    your_message =  forms.CharField(label='Your Message', required=True,
                                widget=forms.Textarea(attrs={'class':'form-control'}))
    captcha = CaptchaField(widget=CaptchaTextInput(attrs={'class':'form-control'}))

    def send_contact_email(self):
        name = self.cleaned_data.get('your_name', 'unknown')
        email = self.cleaned_data['your_email']
        message = self.cleaned_data['your_message']
        
        subject = "Living Hope message from %s" % name
        context = {'name':name, 'email': email,
                    'message':message}
        body = render_to_string('contact_email_template.html', context)
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL,
                 settings.EMAIL_RECIPIENTS, fail_silently=False)
Example #13
0
class QueryForm(forms.ModelForm):
    captcha = CaptchaField(
        help_text='Type the characters you see in the picture',
        widget=CaptchaTextInput())

    class Meta:
        model = Query
        fields = "__all__"
        widgets = {
            'first_name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'First Name'
            }),
            'last_name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Last Name'
            }),
            'phone':
            forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'Phone Number'
            }),
            'email':
            forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': 'Email'
            }),
            'query':
            forms.Textarea(
                attrs={
                    'class': 'form-control',
                    'placeholder': 'Type your query',
                    'cols': 40,
                    'rows': 5
                }),
        }
Example #14
0
class AddTeamForm(forms.Form):
    teamName = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入队伍名字'
        }),
        validators=[add_team_exit_validate],
        error_messages={
            'required': '请填写队伍名字',
            'max_length': '队伍名不得多于8位字符',
            'min_length': '队伍名不得少于3位字符',
        },
        label='队伍名',
        max_length=10,
        min_length=3,
        required=True)
    id = forms.IntegerField(
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入队伍ID'
        }),
        label='队伍ID',
        validators=[add_team_id_exit_validate],
        required=True,
        error_messages={
            'required': '请填写队伍ID',
        },
    )

    captcha = CaptchaField(label='验证码',
                           widget=CaptchaTextInput(attrs={
                               'class': 'form-control',
                               'placeholder': '请输入验证码'
                           }, ),
                           error_messages={
                               "invalid": u"验证码错误",
                               "required": u"请输入验证码",
                           })
Example #15
0
class FeedbackForm(forms.Form):
    name = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={'placeholder': u'Имя'}),
        label=u'Представьтесь:')
    email = EmailField(
        max_length=50,
        widget=forms.EmailInput(attrs={'placeholder': u'*****@*****.**'}),
        label=u'E-mail:')
    phone = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={
            'placeholder': u'+7 (',
            'class': u'form-control masked_input_mobile'
        }),
        required=False,
        label=u'Телефон:')
    text = forms.CharField(max_length=2000,
                           widget=forms.Textarea(attrs={
                               'placeholder': 'Сообщение',
                               'rows': 5
                           }),
                           label=u'Сообщение:')
    attachment = forms.FileField(label=u'Документ:', required=False)
    captcha = CaptchaField(
        widget=CaptchaTextInput(attrs={
            'placeholder': u'Введите код',
            'class': u'form-control captcha-inline'
        }),
        label=u'Код проверки:')

    def clean_attachment(self):
        if self.cleaned_data['attachment']:
            if self.cleaned_data[
                    'attachment'].size > settings.MAX_ATTACH_FEEDBACK_FILE_SIZE:
                raise forms.ValidationError(u'Превышен размер файла')
        return self.cleaned_data['attachment']
Example #16
0
class UserForm(forms.Form):
    username = forms.CharField(
        label='用户',
        max_length=128,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'username',
            'autofocus': ''
        }))
    password = forms.CharField(
        label='密码',
        max_length=256,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'password'
        }))
    # captcha=CaptchaField(label='验证码', widget=CaptchaField(attrs={'class':'form-control', 'placeholder':'username','autofocus':''}))
    captcha = CaptchaField(
        label='验证码',
        widget=CaptchaTextInput(attrs={
            'class': 'form-control',
            'placeholder': '验证码',
            'autofocus': ''
        }))
class ForgetForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '用户名'
        }),
        error_messages={'required': '请输入用户名!'})
    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class': 'form-control mail',
        'placeholder': '邮箱'
    }),
                             error_messages={
                                 'required': '请输入邮箱!',
                                 'invalid': '邮箱不合法!'
                             })
    captcha = CaptchaField(
        widget=CaptchaTextInput(attrs={
            'class': 'form-control user-name',
            'placeholder': '请输入验证码'
        }),
        error_messages={
            'required': '请输入验证码!',
            'invalid': '验证码错误!'
        })
Example #18
0
class LoginForm(forms.Form):
    """!
    Clase que autentica usuarios en el sistema.

    @author William Páez <*****@*****.**>
    @copyright <a href='https://tinyurl.com/y3tfnema'>
        Licencia de Software CENDITEL versión 1.2</a>
    """

    # Username para identificar al usuario con su cédula
    username = IdentificationCardField(validators=[
        validators.RegexValidator(
            r'^[VE][\d]{8}$',
            'Introduzca un número de cédula válido. Solo se permiten \
                    números y una longitud de 8 carácteres. Se agregan ceros \
                    (0) si la longitud es de 7 o menos caracteres.'),
    ],
                                       help_text='V00000000 ó E00000000')

    # Clave de acceso del usuario
    password = forms.CharField(
        label='Contraseña:',
        max_length=128,
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique una contraseña de aceso al sistema'
            }))

    # Campo de validación de captcha
    captcha = CaptchaField(label='Captcha:',
                           widget=CaptchaTextInput(
                               attrs={
                                   'class': 'form-control input-sm',
                                   'placeholder': 'texto de la imagen',
                                   'data-toggle': 'tooltip',
                                   'title': 'Indique el texto de la imagen'
                               }))

    def clean(self):
        """!
        Método que valida si el usuario a autenticar es correcto

        @author William Páez <*****@*****.**>
        """

        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if (not user):
            msg = 'Verifique su usuario o contraseña'
            self.add_error('username', msg)

    class Meta:
        """!
        Meta clase del formulario que establece algunas propiedades

        @author William Páez <*****@*****.**>
        """

        fields = '__all__'
Example #19
0
class PasswordResetForm(forms.Form):
    email = forms.EmailField(
        label=_("E-mail"),
        max_length=254,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    captcha = CustomCatpchaField(
        label=_('Type the letters you see in the box'),
        widget=CaptchaTextInput(attrs={'class': 'form-control'}))

    def clean_email(self):
        """
        Validates that a user exists with the given e-mail address.
        """
        email = self.cleaned_data["email"]
        self_reg = get_setting('module', 'users', 'selfregistration')
        self.email = email
        self.users_cache = User.objects.filter(email__iexact=email,
                                               is_active=True)
        if len(self.users_cache) == 0:
            if self_reg:
                raise forms.ValidationError(
                    mark_safe(
                        _('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve <a href="/accounts/register" >registered</a>?'
                          )))
            else:
                raise forms.ValidationError(
                    _("That e-mail address doesn't have an associated user account."
                      ))
        return email

    def save(
            self,
            email_template_name='registration/password_reset_email_user_list.html',
            **kwargs):
        """
        Generates a one-use only link for resetting password and sends to the designated email.
        The email will contain links for resetting passwords for all accounts associated to the email.
        """
        email_template_name = 'registration/password_reset_email_user_list.html'

        domain_override = kwargs.get('domain_override', False)
        use_https = kwargs.get('use_https', False)
        token_generator = kwargs.get('token_generator',
                                     default_token_generator)

        user_list = []
        for user in self.users_cache:
            user_list.append({
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
            })
        if not domain_override:
            site_name = get_setting('site', 'global', 'sitedisplayname')
        else:
            site_name = domain_override
        site_url = get_setting('site', 'global', 'siteurl')
        t = loader.get_template(email_template_name)
        c = {
            'email': self.email,
            'site_url': site_url,
            'site_name': site_name,
            'user_list': user_list,
            'protocol': use_https and 'https' or 'http',
        }

        from_email = get_setting(
            'site', 'global',
            'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        email = Email(sender=from_email,
                      recipient=user.email,
                      subject=_("Password reset on %s") % site_name,
                      body=t.render(context=c))
        email.send()
Example #20
0
class CaptchaUserCreationForm(UserCreationForm):
    """Create a user signup form with captcha."""
    captcha = CaptchaField(widget=CaptchaTextInput(
        attrs={'placeholder': '验证码'}))
Example #21
0
class RegistroForm(ModelForm):
    """!
    Clase que muestra el formulario de registro de usuarios

    @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
    @date 21-04-2016
    @version 2.0.0
    """

    ## R.I.F. de la Unidad Económica que identifica al usuario en el sistema
    rif = RifField()

    ## Nombre de la Unidad Economica
    nombre_ue = CharField(
        label=_("Nombre de la Unidad Económica: "),
        widget=TextInput(
            attrs={
                'class': 'form-control input-sm',
                'data-rule-required': 'true',
                'data-toggle': 'tooltip',
                'title': _("Nombre de la Unidad Económica a registrar"),
                'readonly': 'readonly',
                'size': '50'
            }),
        required=False)

    ## Cédula de Identidad del usuario
    cedula = CedulaField()

    ## Cargo del usuario dentro de la Unidad Económica
    cargo = CharField(
        label=_("Cargo que ocupa en la U.E.:"),
        max_length=175,
        widget=TextInput(
            attrs={
                'class': 'form-control input-sm',
                'placeholder': _("Cargo en la Empresa"),
                'data-rule-required': 'true',
                'data-toggle': 'tooltip',
                'title': _("Indique el cargo del usuario en la empresa"),
                'size': '50'
            }))

    ## Nombre del usuario
    nombre = CharField(label=_("Nombre"),
                       max_length=30,
                       widget=TextInput(
                           attrs={
                               'class': 'form-control input-sm',
                               'placeholder': _("Nombres del usuario"),
                               'data-rule-required': 'true',
                               'data-toggle': 'tooltip',
                               'title': _("Indique el Nombre"),
                               'size': '50'
                           }))

    ## Apellido del usuario
    apellido = CharField(label=_("Apellido"),
                         max_length=30,
                         widget=TextInput(
                             attrs={
                                 'class': 'form-control input-sm',
                                 'placeholder': _("Apellidos del usuario"),
                                 'data-rule-required': 'true',
                                 'data-toggle': 'tooltip',
                                 'title': _("Indique el Apellido"),
                                 'size': '50'
                             }))

    ## Número telefónico de contacto con el usuario
    telefono = CharField(
        label=_("Teléfono"),
        max_length=20,
        widget=TextInput(
            attrs={
                'class':
                'form-control input-sm',
                'placeholder':
                '(058)-000-0000000',
                'data-rule-required':
                'true',
                'data-toggle':
                'tooltip',
                'size':
                '15',
                'title':
                _("Indique el número telefónico de contacto con el usuario"),
                'data-mask':
                '(000)-000-0000000'
            }),
        help_text=_("(país)-área-número"))

    ## Correo electrónico de contacto con el usuario
    correo = EmailField(
        label=_("Correo Electrónico"),
        max_length=75,
        widget=EmailInput(
            attrs={
                'class':
                'form-control input-sm email-mask',
                'placeholder':
                _("Correo de contacto"),
                'data-toggle':
                'tooltip',
                'size':
                '50',
                'data-rule-required':
                'true',
                'title':
                _("Indique el correo electrónico de contacto con el usuario. "
                  "No se permiten correos de hotmail")
            }))

    ## Contraseña del usuario
    password = CharField(
        label=_("Contraseña"),
        max_length=128,
        widget=PasswordInput(
            attrs={
                'class': 'form-control input-sm',
                'placeholder': _("Contraseña de acceso"),
                'data-rule-required': 'true',
                'data-toggle': 'tooltip',
                'size': '50',
                'title': _("Indique una contraseña de aceso al sistema"),
                'onkeyup': 'passwordStrength(this.value)'
            }))

    ## Confirmación de contraseña de acceso
    verificar_contrasenha = CharField(
        label=_("Verificar Contraseña"),
        max_length=128,
        widget=PasswordInput(
            attrs={
                'class': 'form-control input-sm',
                'placeholder': _("Contraseña de acceso"),
                'data-rule-required': 'true',
                'data-toggle': 'tooltip',
                'size': '50',
                'title': _(
                    "Indique nuevamente la contraseña de aceso al sistema")
            }))

    ## Campo para la validación del captcha
    captcha = CaptchaField(
        label=_(u"Captcha"),
        widget=CaptchaTextInput(
            attrs={
                'class': 'form-control input-sm',
                'placeholder': _("Texto de la imagen"),
                'style': 'min-width: 0; width: auto; display: inline;',
                'data-toggle': 'tooltip',
                'title': _(u"Indique el texto de la imagen")
            }))

    class Meta:
        model = User
        exclude = [
            'fecha_modpass', 'username', 'first_name', 'last_name', 'email',
            'date_joined'
        ]

    def clean_rif(self):
        """!
        Método que permite validar el campo de rif

        @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
        @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
        @date 27-04-2016
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Devuelve un mensaje de error en caso de que el rif no sea válido o no se encuentre registrado en el
                SENIAT, en caso contrario devuelve el valor actual del campo
        """
        rif = self.cleaned_data['rif']

        if rif[0] not in TIPO_PERSONA_LIST:
            raise forms.ValidationError(_("Tipo de RIF incorrecto"))
        elif User.objects.filter(username=rif):
            raise forms.ValidationError(_("El RIF ya se encuentra registrado"))
        elif not rif[1:].isdigit():
            raise forms.ValidationError(_("El RIF no es correcto"))

        return rif

    def clean_cedula(self):
        """!
        Método que permite validar la cedula de identidad del usuario a registrar

        @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
        @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
        @date 02-05-2016
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Devuelve un mensaje de error en caso de la cedula de identidad sea incorrecta
        """
        cedula = self.cleaned_data['cedula']

        if cedula[0] not in NACIONALIDAD_LIST:
            raise forms.ValidationError(_("La nacionalidad no es correcta"))
        elif not cedula[1:].isdigit():
            raise forms.ValidationError(
                _("El número de cédula no es correcto"))

        return cedula

    def clean_correo(self):
        """!
        Método que permite validar el campo de correo electronico

        @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
        @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
        @date 02-05-2016
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Devuelve un mensaje de error en caso de que el correo electronico ya se encuentre registrado
        """
        correo = self.cleaned_data['correo']

        if User.objects.filter(email=correo):
            raise forms.ValidationError(_("El correo ya esta registrado"))

        return correo

    def clean_password(self):
        """!
        Método que permite validar el campo de password

        @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
        @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
        @date 02-05-2016
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Devuelve un mensaje de error en caso de que la fortaleza de la contraseña sea inferior al minimo
                establecido
        """
        password_meter = self.data['passwordMeterId']
        if int(password_meter) < FORTALEZA_CONTRASENHA:
            raise forms.ValidationError(_("La contraseña es débil"))
        return self.cleaned_data['password']

    def clean_verificar_contrasenha(self):
        """!
        Método que permite validar el campo de verificar_contrasenha

        @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
        @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
        @date 02-05-2016
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Devuelve un mensaje de error en caso de que la contrasenha no pueda ser verificada
        """
        verificar_contrasenha = self.cleaned_data['verificar_contrasenha']
        contrasenha = self.data['password']
        if contrasenha != verificar_contrasenha:
            raise forms.ValidationError(_("La contraseña no es la misma"))

        return verificar_contrasenha
Example #22
0
class RegisterForm(forms.Form):
    userid = forms.CharField(label="学号",
                             min_length=8,
                             max_length=8,
                             widget=widgets.TextInput(attrs={
                                 "class": "form-control",
                                 "placeholder": "请输入学号"
                             }),
                             error_messages={
                                 "min_length": "请输入8位学号",
                                 "max_length": "请输入8位学号",
                                 "required": "学号不能为空"
                             })
    username = forms.CharField(label="姓名",
                               max_length=150,
                               min_length=1,
                               widget=widgets.TextInput(attrs={
                                   "class": "form-control",
                                   "placeholder": "请输入姓名"
                               }),
                               error_messages={
                                   "min_length": "姓名不能小于1个字符",
                                   "max_length": "姓名不能大于150个字符",
                                   "required": "姓名不能为空"
                               })
    email = forms.EmailField(label="邮箱",
                             max_length=150,
                             min_length=1,
                             widget=widgets.EmailInput(attrs={
                                 "class": "form-control",
                                 "placeholder": "请输入邮箱"
                             }),
                             error_messages={
                                 "min_length": "邮箱不能小于1个字符",
                                 "max_length": "邮箱不能大于150个字符",
                                 "required": "邮箱不能为空",
                                 "invalid": "请输入正确的邮箱格式"
                             })
    password1 = forms.CharField(
        label="密码",
        max_length=150,
        min_length=1,
        widget=widgets.PasswordInput(attrs={
            "class": "form-control",
            "placeholder": "请输入密码"
        }),
        error_messages={
            "min_length": "密码不能小于1个字符",
            "max_length": "密码不能大于150个字符",
            "required": "密码不能为空"
        })
    password2 = forms.CharField(
        label="密码确认",
        max_length=150,
        min_length=1,
        widget=widgets.PasswordInput(attrs={
            "class": "form-control",
            "placeholder": "请再次输入密码"
        }),
        error_messages={
            "min_length": "密码不能小于1个字符",
            "max_length": "密码不能大于150个字符",
            "required": "密码不能为空"
        })

    captcha = CaptchaField(label="验证码",
                           widget=CaptchaTextInput(attrs={
                               "class": "form-control",
                               "placeholder": "验证码"
                           }))

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("两次密码不匹配, 请重新输入!")
        return password2
Example #23
0
class ProfileForm(forms.ModelForm, LocationForm):
    """!
    @author William Páez <*****@*****.**>
    @copyright <a href='https://tinyurl.com/y3tfnema'>
        Licencia de Software CENDITEL versión 1.2</a>
    """

    # Username para identificar al usuario con su cédula
    username = IdentificationCardField(validators=[
        validators.RegexValidator(
            r'^[VE][\d]{8}$',
            'Introduzca un número de cédula válido. Solo se permiten \
                    números y una longitud de 8 carácteres. Se agregan ceros \
                    (0) si la longitud es de 7 o menos caracteres.'),
    ],
                                       help_text='V00000000 ó E00000000')

    # Nombres del usuario
    first_name = forms.CharField(label='Nombres:',
                                 max_length=100,
                                 widget=forms.TextInput(
                                     attrs={
                                         'class': 'form-control input-sm',
                                         'data-toggle': 'tooltip',
                                         'title': 'Indique los Nombres',
                                     }))

    # Apellidos del usuario
    last_name = forms.CharField(label='Apellidos:',
                                max_length=100,
                                widget=forms.TextInput(
                                    attrs={
                                        'class': 'form-control input-sm',
                                        'data-toggle': 'tooltip',
                                        'title': 'Indique los Apellidos',
                                    }))

    # Correo del usuario
    email = forms.EmailField(
        label='Correo Electrónico:',
        max_length=100,
        widget=forms.EmailInput(
            attrs={
                'class': 'form-control input-sm email-mask',
                'data-toggle': 'tooltip',
                'data-rule-required': 'true',
                'title': 'Indique el correo electrónico de contacto'
            }))

    # Teléfono del usuario
    phone = forms.CharField(
        label='Teléfono:',
        max_length=15,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique el número telefónico de contacto',
                'data-mask': '+00-000-0000000'
            }),
        validators=[
            validators.RegexValidator(
                r'^\+\d{2}-\d{3}-\d{7}$',
                'Número telefónico inválido. Solo se permiten números \
                    y los símbolos: + -'),
        ],
        help_text='+58-416-0000000')

    # Profesión del usuario
    profession = forms.CharField(label='Profesión:',
                                 max_length=100,
                                 widget=forms.TextInput(
                                     attrs={
                                         'class': 'form-control input-sm',
                                         'data-toggle': 'tooltip',
                                         'title': 'Indique la profesión',
                                     }),
                                 required=False)

    # Organización que pertenece el usuario
    organization = forms.CharField(label='Organización:',
                                   max_length=100,
                                   widget=forms.TextInput(
                                       attrs={
                                           'class': 'form-control input-sm',
                                           'data-toggle': 'tooltip',
                                           'title': 'Indique la organización',
                                       }),
                                   required=False)

    # Cuenta de twitter del usuario
    twitter_account = forms.CharField(
        label='Cuenta de Twitter:',
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique la cuenta de twitter',
            }),
        required=False)

    # Cuenta de facebook del usuario
    facebook_account = forms.CharField(
        label='Cuenta de Facebook:',
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique la cuenta de facebook',
            }),
        required=False)

    # Clave de acceso del usuario
    password = forms.CharField(
        label='Contraseña:',
        max_length=128,
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique una contraseña de aceso al sistema'
            }))

    # Confirmación de clave de acceso del usuario
    confirm_password = forms.CharField(
        label='Confirmar Contraseña:',
        max_length=128,
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control input-sm',
                'data-toggle': 'tooltip',
                'title': 'Indique nuevamente la contraseña de aceso al sistema'
            }))

    # Campo de validación de captcha
    captcha = CaptchaField(label='Captcha:',
                           widget=CaptchaTextInput(
                               attrs={
                                   'class': 'form-control input-sm',
                                   'placeholder': 'texto de la imagen',
                                   'data-toggle': 'tooltip',
                                   'title': 'Indique el texto de la imagen'
                               }))

    def clean_email(self):
        """!
        Función que permite validar si el correo del usuario ya esta registrado
        en el sistema

        @author William Páez <*****@*****.**>
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Mensaje de error en caso de que el correo ya esté registrado
            en el sistema
        """

        email = self.cleaned_data['email']
        if User.objects.filter(email=email):
            raise forms.ValidationError('El correo ya esta registrado')
        return email

    def clean_confirm_password(self):
        """!
        Función que permite validar si ambas contraseñas son iguales

        @author William Páez <*****@*****.**>
        @param self <b>{object}</b> Objeto que instancia la clase
        @return Mensaje de error en caso de que las contraseñas sean distintas
        """

        confirm_password = self.cleaned_data['confirm_password']
        password = self.cleaned_data.get('password')
        if password != confirm_password:
            raise forms.ValidationError('La contraseña no es la misma')

        return confirm_password

    class Meta:
        """!
        Meta clase del formulario que establece algunas propiedades

        @author William Páez <*****@*****.**>
        """

        model = User
        fields = [
            'username', 'first_name', 'last_name', 'email', 'phone',
            'profession', 'organization', 'twitter_account',
            'facebook_account', 'password', 'confirm_password', 'captcha'
        ]
Example #24
0
class RegistrationCustomForm(RegistrationForm):
    first_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    company = forms.CharField(max_length=100,
                              widget=forms.TextInput(attrs={
                                  'size': '40',
                                  'class': 'form-control'
                              }),
                              required=False)
    phone = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    address = forms.CharField(max_length=150,
                              widget=forms.TextInput(attrs={
                                  'size': '40',
                                  'class': 'form-control'
                              }),
                              required=False)
    city = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    state = forms.CharField(max_length=50,
                            widget=forms.TextInput(attrs={
                                'size': '10',
                                'class': 'form-control'
                            }),
                            required=False)
    country = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    zipcode = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    captcha = CaptchaField(
        label=_('Type the code below'),
        widget=CaptchaTextInput(attrs={'class': 'form-control'}))

    allow_same_email = None
    similar_email_found = False

    def __init__(self, *args, **kwargs):
        self.allow_same_email = kwargs.pop('allow_same_email', False)

        super(RegistrationCustomForm, self).__init__(*args, **kwargs)

    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        password_regex = get_setting('module', 'users',
                                     'password_requirements_regex')
        password_requirements = get_setting('module', 'users', 'password_text')
        if password_regex:
            if not re.match(password_regex, password1):
                raise forms.ValidationError(
                    mark_safe(
                        _("The password does not meet the requirements: %(p)s"
                          % {'p': password_requirements})))

        return password1

    def clean(self):
        if self._errors:
            return
        user = User.objects.filter(email=self.cleaned_data['email'])
        if user and not self.allow_same_email:
            self.similar_email_found = True
            raise forms.ValidationError(_("Similar emails found"))

        return self.cleaned_data

    def save(self, profile_callback=None, event=None):
        #
        #new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
        #                                                            password=self.cleaned_data['password1'],
        # create inactive user                                                           email=self.cleaned_data['email'])
        new_user = User.objects.create_user(self.cleaned_data['username'],
                                            self.cleaned_data['email'],
                                            self.cleaned_data['password1'])

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.is_active = False
        new_user.save()
        # create registration profile
        registration_profile = RegistrationProfile.objects.create_profile(
            new_user)
        send_registration_activation_email(new_user,
                                           registration_profile,
                                           event=event)

        new_profile = Profile(
            user=new_user,
            company=self.cleaned_data['company'],
            phone=self.cleaned_data['phone'],
            address=self.cleaned_data['address'],
            city=self.cleaned_data['city'],
            state=self.cleaned_data['state'],
            country=self.cleaned_data['country'],
            zipcode=self.cleaned_data['zipcode'],
        )
        user_hide_default = get_setting('module', 'users', 'usershidedefault')
        if user_hide_default:
            new_profile.hide_in_search = 1
            new_profile.hide_address = 1
            new_profile.hide_email = 1
            new_profile.hide_phone = 1

        new_profile.creator = new_user
        new_profile.creator_username = new_user.username
        new_profile.owner = new_user
        new_profile.owner_username = new_user.username
        new_profile.save()
        sf_id = create_salesforce_contact(new_profile)

        return new_user
Example #25
0
class commentForm(forms.ModelForm):
    captcha = CaptchaField(widget=CaptchaTextInput(attrs={'class': "form-captcha",
                                                          'placeholder': '验证码'}))
    class Meta:
        model=Comment
        fields=['name','email','text','post']
Example #26
0
class FeedBackForm(forms.ModelForm):
    captcha = CaptchaField(
        label=u'Код защиты',
        widget=CaptchaTextInput(attrs={
            'placeholder': 'Код защиты',
            'class': 'span8',
            'required': True
        }))

    def __init__(self, *args, **kwargs):
        super(FeedBackForm, self).__init__(*args, **kwargs)

    class Meta:
        model = FeedBackItem
        fields = ('name', 'email', 'phone', 'captcha', 'msg')
        widgets = {
            'msg':
            forms.Textarea(
                attrs={
                    'placeholder': "Сообщение",
                    'rows': "8",
                    'class': "span12",
                    'required': True
                }),
            'name':
            forms.TextInput(attrs={
                'placeholder': "ФИО",
                'class': "span12",
                'required': True
            }),
            'email':
            forms.TextInput(attrs={
                'placeholder': "Email",
                'class': 'span12',
                'required': True
            }),
            'phone':
            forms.TextInput(attrs={
                'placeholder': "Телефон",
                'class': 'span12'
            })
        }

    def clean_name(self):
        name = self.cleaned_data['name']
        if len(name) < 3:
            raise forms.ValidationError(u'Слишком короткое ФИО')
        return name

    def clean_email(self):
        email = self.cleaned_data['email']
        if email:
            r = re.compile(
                '^[0-9a-zA-Z]+[-\._0-9a-zA-Z]*@[0-9a-zA-Z]+[-\._^0-9a-zA-Z]*[0-9a-zA-Z]+[\.]{1}[a-zA-Z]{2,6}$'
            )
            if not r.findall(email):
                raise forms.ValidationError(u'Некорректный E-mail')
        return email

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if phone:
            r = re.compile(
                '^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$')
            if not r.findall(phone):
                raise forms.ValidationError(u'Некорректный номер телефона')
        return phone

    def clean_msg(self):
        msg = self.cleaned_data['msg']
        msg = cgi.escape(msg)
        if len(msg) < 10:
            raise forms.ValidationError(u'Слишком короткое сообщение')
        return msg


################################################################################################################
################################################################################################################
Example #27
0
class CaptchaModelForm(forms.ModelForm):
    captcha = CaptchaField(widget=CaptchaTextInput(attrs={
        'class': 'form-control',
    }))
Example #28
0
class UserForm(forms.ModelForm):
    #错误信息
    error_messages = {
        'duplicate_username': "******",
        'password_mismatch': "You need to enter two identical passwords.",
        'duplicate_email': 'existing email.'
    }

    username = forms.RegexField(
        max_length=40,
        regex=r'^[\w.@+-]+$',
        #错误信息 invalid 表示username不合法的错误信息, required 表示没填的错误信息
        error_messages={
            'invalid': "Can only content digits, letters and the characters including @/./+/-/_",
            'required': "Username is need"
        },
        widget=forms.TextInput(attrs={'class': 'input--style'}))
    email = forms.EmailField(error_messages={
        'invalid': "wrong email format",
        'required': 'email is needed'
    })

    motto = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'input--style'})
    )

    email = forms.EmailField(
        widget=forms.TextInput(attrs={'class': 'input--style'})
    )

    graduationtime = forms.DateField(
        widget=forms.DateInput(attrs={'class': 'input--style'})
    )

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'input--style'}), error_messages={'required': "password is needed"})
    password_confirm = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'input--style'}), error_messages={'required': "confirmed password is needed"})

    captcha = CaptchaField(
        widget=CaptchaTextInput(attrs={'class': 'input--style'}),
        error_messages={'invalid': 'wrong validation code'})

    class Meta:
        model = User
        fields = ("username", "email","sex","major",'graduationtime','motto')

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages["duplicate_username"])

    def clean_password_confirm(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError(
                self.error_messages["password_mismatch"])
        return password_confirm

    def clean_email(self):
        email = self.cleaned_data["email"]

        #判断是这个email 用户是否存在
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(self.error_messages["duplicate_email"])

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user
Example #29
0
class FeedBackForm(forms.ModelForm):
    """
    во фронтенде меняем поле сообщения формы обратной связи с RichTextField на Textarea
    """
    msg = forms.CharField(label=u'Сообщение',
                          max_length=1000,
                          widget=forms.Textarea(
                              attrs={
                                  'rows': "4",
                                  'class': "span12",
                                  'placeholder': "Ваше сообщение",
                                  'required': True
                              }))
    captcha = CaptchaField(label=u'Код защиты',
                           widget=CaptchaTextInput(attrs={
                               'placeholder': 'Код защиты',
                               'required': True
                           }))

    class Meta:
        model = FeedBackItem
        fields = ('name', 'email', 'phone', 'msg', 'captcha')
        widgets = {
            'name': forms.TextInput(attrs={
                'placeholder': "ФИО",
                'required': True
            }),
            'email': forms.TextInput(attrs={'placeholder': "E-mail"}),
            'phone': forms.TextInput(attrs={'placeholder': "Телефон"})
        }

    def clean_name(self):
        name = self.cleaned_data['name']
        if len(name) < 3:
            raise forms.ValidationError(u'Слишком короткое ФИО')
        return name

    def clean_email(self):
        email = self.cleaned_data['email']
        if email:
            r = re.compile(
                '^[0-9a-zA-Z]+[-\._0-9a-zA-Z]*@[0-9a-zA-Z]+[-\._^0-9a-zA-Z]*[0-9a-zA-Z]+[\.]{1}'
                '[a-zA-Z]{2,6}$')
            if not r.findall(email):
                raise forms.ValidationError(u'Некорректный E-mail')
        return email

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if phone:
            r = re.compile(
                '^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{6,10}$')
            if not r.findall(phone):
                raise forms.ValidationError(u'Некорректный номер телефона')
        return phone

    def clean_msg(self):
        msg = self.cleaned_data['msg']
        msg = cgi.escape(msg)
        if len(msg) < 10:
            raise forms.ValidationError(u'Слишком короткое сообщение')
        return msg


####################################################################################################
####################################################################################################
Example #30
0
class CaptchaAuthenticationForm(AuthenticationForm):
    """Create a user login form with captcha."""
    captcha = CaptchaField(widget=CaptchaTextInput(
        attrs={'placeholder': '验证码'}))