Django用户注册验证无效

时间:2013-04-10 19:55:01

标签: django django-models django-views django-users

您好我想在用户存在并且密码与密码确认字段匹配时开发用户注册验证。不幸的是,验证不起作用。例如,如果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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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