2

您好,如果用户存在并且密码与密码确认字段匹配,我想对用户注册进行验证。不幸的是,验证不起作用。例如,如果 2 个密码不匹配,则无论如何都会使用第一个密码完成注册。如果出现问题,我想重新加载突出显示问题的注册表单。

表格:

class RegistrationForm(forms.Form):
    username = forms.CharField(label=u'Username', max_length=30)
    first_name = forms.CharField(label=u'First Name', max_length=30)
    last_name = forms.CharField(label=u'Last Name', max_length=30)
    email = forms.EmailField(label=u'Email')
    password1 = forms.CharField(
                                label=u'Password',
                                widget=forms.PasswordInput()
                                )
    password2 = forms.CharField(
                                label=u'Password (Again)',
                                widget=forms.PasswordInput()
                                )

def clean_password2(self):
    if 'password1' in self.cleaned_data:
        password1 = self.cleaned_data['password1']
        password2 = self.cleaned_data['password2']
        if password1 == password2:
            return password2

    raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
    username = self.cleaned_data['username']
    if not re.search(r'^\w+$', username):
        raise forms.ValidationError('Username can only contain '
                                    'alphanumeric characters and the underscore.')
    try:
           User.objects.get(username=username)
    except User.DoesNotExist:
            return username
    raise forms.ValidationError('Username is already taken.')

风景:

def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                                            username=form.cleaned_data['username'],
                                            password=form.cleaned_data['password1'],
                                            email=form.cleaned_data['email']
                                            )
            UserProfile.first_name=form.cleaned_data['first_name']
            created = UserProfile.objects.get_or_create(
                                                        user_id=user.id, first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']    )
            return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {
                               'form': form
                               })
    return render_to_response(
                              'registration/register.html', variables)
4

2 回答 2

0
class RegistrationForm(forms.Form):
    //fields

def clean(self):
    cleaned_data = super(RegistrationForm, self).clean()
    username = cleaned_data.get("username")
    password1 = cleaned_data.get("password1")
    password1 = cleaned_data.get("password1")

    #validate username 
    user = User.objects.filter(username=username)
    if user:
        raise forms.ValidationError(
            "That user is already taken , please select another ")
    elif not re.search(r'^\w+$', username):
        raise forms.ValidationError(
            "Username can only contain"
            "alphanumeric characters and the underscore.")

    #validate password
    if password1 != password1:
        raise forms.ValidationError(
            "Your current and confirm password do not match.")

    return cleaned_data
于 2013-04-11T03:39:14.337 回答
0

我使用这个有效的简单验证。

def validate(self, value):
    data = self.get_initial()
    username = data.get("username")
    email = data.get("email")
    password = data.get("password")
    confirm_password = data.get("confirm_password")
    max_similarity = 0.7
    user_qs = User.objects.filter(email=username)
    if user_qs.exists():
        raise ValidationError("Username already exist")
        if(password != confirm_password):
            raise ValidationError("Password and Confirm password does not match")
    if SequenceMatcher(a=password.lower(), b=username.lower()).quick_ratio() > max_similarity:
        raise serializers.ValidationError("The password is too similar to the username.")
    if SequenceMatcher(a=password.lower(), b=email.lower()).quick_ratio() > max_similarity:
        raise serializers.ValidationError("The password is too similar to the email.")
    return data

附加验证:您也可以通过添加这个来添加 django 的一些默认验证。这将检查密码的最小长度和最大字符串和最大整数。

def validate_password(self, value):
    try:
        validate_password(value)
    except ValidationError as exc:
        raise serializers.ValidationError(str(exc))
    return value
于 2018-01-08T05:39:17.390 回答