django注册视图无法正常工作

时间:2017-03-05 09:55:12

标签: django django-templates django-views

我想创建一个注册视图,所以它需要用户名,密码和电子邮件进行注册,我使用Django用户模型,但它给了我一个错误。

AttributeError at /signup/
'SignUpForm' object has no attribute 'cleaned_data'

请告诉我如何解决这个问题,

forms.py

class SignUpForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':
        'Confirm Password'}), label="Confirm Password")

    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        super(SignUpForm, self).__init__(*args, **kwargs)
        self.fields['username'].validators.append(ForbiddenUsernamesValidator)
        self.fields['username'].validators.append(InvalidUsernameValidator)
        self.fields['username'].validators.append(UniqueUsernameIgnoreCaseValidator)
        self.fields['email'].validators.append(UniqueEmailValidator)

    def clean(self):
        super(SignUpForm, self).clean()
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and password != confirm_password:
            self._errors['password'] = self.error_class(['Passwords don\'t match'])
        return self.cleaned_data

views.py

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST or None)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            email = form.cleaned_data.get('email')
            print(username)
            print(password)
            print(email)
            messages.add_message(request, messages.SUCCESS, 'YOU ARE REGISTRED SUCCESSFULLY')
            return render(request, 'authentication/signup.html', {})
        else:

            return render(request, 'authentication/signup.html', {'form': form})
    else:
        return render(request, 'authentication/signup.html', {'form': SignUpForm})

1 个答案:

答案 0 :(得分:0)

 def clean(self):
        self.cleaned_data = super(SignUpForm, self).clean()
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and password != confirm_password:
            self._errors['password'] = self.error_class(['Passwords don\'t match'])
        return self.cleaned_data