自定义注册表格。确认密码

时间:2019-09-09 10:25:07

标签: django django-forms django-registration django-custom-user

我为注册用户使用了自定义表格。我想要验证以确认密码。 forms.py:

class RegistrationForm(UserCreationForm):
    '''Register for new users'''
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = get_user_model()
        fields = {'username', 'password1', 'password2', 'email', 'first_name', 'last_name'}

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            user.save()

        return user

模板:

<div class="input-group register">
     {{ form.password.errors }}
     <label for="id_password1">Password: </label>
     {{ form.password1 }}
</div>
<div class="input-group register">
    {{ form.password.errors }}
    <label for="id_password2">Confirm password: </label>
    {{ form.password2 }}                            
</div>

views.py

def registration_view(request):
context = {}
context.update(csrf(request))
context['form'] = RegistrationForm()

if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        newuser = auth.authenticate(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password2']
        )
        auth.login(request, newuser)
        return redirect('home')
    else:
        context['form'] = form

return render(request, '/registration.html', context)

如何添加密码验证(也请确认密码)?

3 个答案:

答案 0 :(得分:1)

您从UserCreationForm [GitHub]继承。此表单已经为您完成了任务。

确实:clean_password2将验证两个密码是否相同:

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

_post_clean函数将验证密码是否为有效密码:

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error('password2', error)

最后在save()中,它将使用.set_password()来设置密码。这是必要的,因为Django的User模型将像其他任何好的用户模型一样,哈希密码。

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

因此,您不应干预这些。您在这里只想添加first_namelast_name。因此,您可以通过以下方式添加该逻辑:

class RegistrationForm(UserCreationForm):
    '''Register for new users'''
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

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

仅此而已,因为ModelForm会解决这个问题。

请注意,视图中的authenticate可能不是必需的,因为如果构造用户,则它应该进行身份验证。您可以在此处login

def registration_view(request):
    context = {}
    context.update(csrf(request))
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            newuser = form.save()
            auth.login(request, newuser)
        return redirect('home')
    else:
        form = RegistrationForm()
    context['form'] = form
    return render(request, '/registration.html', context)

答案 1 :(得分:1)

尝试在您的注册模板中使用它

<form method="post" id="register-account-form">
                {% csrf_token %}

                {% for field in form %}

                        {% if field.help_text %}
                            <div class="notification error closeable">
                            <small style="color: grey">{{ field.help_text }}</small>
                            <a class="close" href="#"></a>
                            </div>
                        {% endif %}
                        {% for error in field.errors %}
                            <div class="notification error closeable">
                            <p style="color: red">{{ error }}</p>
                            <a class="close" href="#"></a>
                            </div>

                        {% endfor %}
                {% endfor %}


                <div class="input-with-icon-left">
                    <i class="icon-feather-user"></i>
                    {{ form.username }}
                </div>

答案 2 :(得分:0)

我发现了错误

<div class="input-group register">
    {{ form.password1.errors }}
     <label for="id_password1">Пароль: </label>
     {{ form.password1 }}
 </div>
 <div class="input-group register">
     {{ form.password2.errors }}
     <label for="id_password2">Подтвердите пароль: </label>
     {{ form.password2 }}                            
 </div>