Django注册表在密码无法通过验证时出错

5kgi1eie  于 2022-12-05  发布在  Go
关注(0)|答案(1)|浏览(170)

我正在尝试使用自动登录进行用户注册。当密码不同或未通过验证时,表单没有消息。它抛出错误:

AttributeError at /accounts/register/
'AnonymousUser' object has no attribute '_meta'

我认为错误来自login(request, self.object)行。我已经尝试通过覆盖表单中的clean()方法来修复该问题,但没有成功。我不知道该怎么做。
我模特:

class AppUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
    email = models.EmailField(
        unique=True,
        blank=False,
        null=False,
    )

    is_staff = models.BooleanField(
        default=False,
        blank=False,
        null=False,
    )

    USERNAME_FIELD = 'email'

    objects = AppUserManager()

我表单:

class SignUpForm(auth_forms.UserCreationForm):
    class Meta:
        model = UserModel
        fields = (UserModel.USERNAME_FIELD, 'password1', 'password2',)
        field_classes = {
            'email': auth_forms.UsernameField,
        }

我观点:

class SignUpView(views.CreateView):
    template_name = 'accounts/user/register-user-page.html'
    form_class = SignUpForm
    success_url = reverse_lazy('home')

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        login(request, self.object)

        return response
h43kikqp

h43kikqp1#

您需要覆盖form_valid()而不是post()

from django.http import HttpResponseRedirect

def form_valid(self, form):
    user = form.save() #save the user
    login(request, user)
    return HttpResponseRedirect(self.get_success_url())

相关问题