首页 > 解决方案 > /accounts/signup/ Manager 的 AttributeError 不可用;'auth.User' 已替换为 'accounts.CustomUser'

问题描述

我有一个自定义注册表单SignupForm,用于检查email自定义用户对象是否存在CustomUser并引发一个ValidationErrorif 存在。但是当我尝试提出错误时,我得到AttributeError at /accounts/signup/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'.

这是我的代码。

表格.py

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ValidationError

from django.contrib.auth import get_user_model


class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

视图.py

from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import SignupForm
from .models import CustomUser

...
# other views and imports
...

class CustomSignup(CreateView):
    form_class = SignupForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

模型.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username

设置.py

AUTH_USER_MODEL = "accounts.CustomUser"

我错过了什么?

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


基本上你缺少 ModelForm Meta

尝试这个

class SignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

    email = forms.CharField(
        widget=forms.EmailInput(
        attrs={
            'class': 'input',
            'placeholder': 'bearclaw@example.com'
        }
    ))

    ...
    # other fields (username and password)
    ...

    def clean(self):
       User = get_user_model()
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("An account with this email exists.")
       return self.cleaned_data

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

推荐阅读