如果form.is_valid()不调用clean(self)方法

时间:2019-04-22 20:36:54

标签: django django-forms

我有一个RegisterUserForm绑定到一个CustomUser(扩展AbstractUser)。在保存用户之前,我想检查password1和password2是否相等,但是未调用clean(self)方法。即使密码不同,也会创建用户。 我读了很多问题,尝试了很多事情,但找不到答案。我的代码在下面

我尝试添加一个init和一个save方法,但是仍然无法正常工作。

class RegisterUserForm(forms.ModelForm):
    password1=forms.CharField(label=_("password"), min_length=4)
    password2=forms.CharField(label=_("repeat password"), min_length=4)

    class Meta:
        model = CustomUser
        fields = ('first_name', 'last_name', 'email', 'password1','password2')


        def save(self, *args, **kwargs):
            self.full_clean()
            return super().save(*args, **kwargs)

        def clean(self):
            cleaned_data = super().clean()
            print("clean is called")
            password1 = form.cleaned_data.get("password1")
            password2 = form.cleaned_data.get("password2")
            if password1 and password2 and password1 != password2:
                raise ValidationError('password_mismatch')

            return self.cleaned_data

我的观点是

def register(request):
    if request.method=='POST':
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password1'])
            user.save()
            email = user.email
            messages.success(request, f'user with {email} created successfully')
            return redirect('home')
    else:
        form = RegisterUserForm()
    return render(request, 'users/register.html', {'form':form })

0 个答案:

没有答案