object没有属性'clean_data'错误

时间:2016-04-21 21:24:30

标签: python django

我在清理数据时一直没有获取属性。仅当我尝试POST到表单以注册用户时才会出现此错误。

虽然我可以使用内置注册视图和表单的django,但我决定使用内置版本,因为我希望以后更容易使用扩展的自定义用户模型。 的观点:

def register(request):

if request.method == 'POST':
    user_form = UserRegistrationForm(request.POST)
    if user_form.is_valid():

        new_user = user_form.save(commit=False)

        new_user.set_password(
            user_form.clean_data['password'])

        new_user.save()

        profile = Profile.objects.create(user=new_user)

        return render(request, 
            'account/register_done.html', 
            {'new_user':new_user})
else:
    user_form = UserRegistrationForm()

return render(request, 
                'registration.html', 
            {'user_form': user_form})

形式:

from django import forms
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm   


class UserRegistrationForm(forms.ModelForm):

    password = forms.CharField(label='Password',
        widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password', 
        widget=forms.PasswordInput)

class Meta:
    model = User
    fields = ('username', 'first_name',
        'email')

    def clean_password2(self):
        cd = self.clean_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('Passwords don\'t match.')
        return cd['password2']

0 个答案:

没有答案