自定义django用户注册

时间:2018-01-24 11:57:59

标签: django

我正在做一个用户注册功能,这是视图

from django.http import HttpResponseGone    
from .forms import RegisterForms   
from django.shortcuts import render    
def register(request):
    if request.method == 'POST':
        user_forms = RegisterForms(request.POST)
        if user_forms.is_valid():
            new_userform = user_forms.save(commit=False)
            new_userform.set_password(user_forms.cleaned_data['password'])
            new_userform.save()
            return HttpResponseGone('注册成功')
        else:
            return HttpResponseGone('注册失败')
    else:
        user_forms = RegisterForms()
        return render(request,'account/register.html',{'form':user_forms})

这是表格

from django import forms    
from django.contrib.auth.models import User    
class RegisterForms(forms.ModelForm):
    password = forms.CharField(label='Password',widget=forms.PasswordInput)
    password2 = forms.CharField(label='password again',widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = ('username','email')
    def clean_password2(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('密码输入不一致,请从新输入')
        else:
            return cd['password']

这是html

<p>欢迎注册</p>
<form action="." method="post">
    {% csrf_token %}
    <p>username {{ form.username }}</p>
    <p>email {{ form.email }}</p>
    <p>password {{ form.password }}</p>
    <p>password again {{ form.password2 }}</p>
    <input type="submit" value="register">
</form>

我发现如果我将views文件中clean_password2方法的名称更改为clean_password,我无法以

的形式获取password2的值

这是错误的信息[在此处输入图像说明] [4]

我的英语不是很好我希望有人可以帮助我谢谢谢谢谢谢

1 个答案:

答案 0 :(得分:1)

from django import forms

from django.contrib.auth.models import User

class RegisterForms(forms.ModelForm):
    password = forms.CharField(label='Password',widget=forms.PasswordInput)
    password2 = forms.CharField(label='password again',widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = ('username','email','password','password2')
    def clean(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('密码输入不一致,请从新输入')
        else:
            return cd

简而言之,在这种情况下使用干净的方法。