/accounts/signup/ Manager 处的 AttributeError 不可用;

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


这是我的代码。


forms.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

views.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'

models.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

settings.py


AUTH_USER_MODEL = "accounts.CustomUser"

我错过了什么?


大话西游666
浏览 57回答 1
1回答

胡子哥哥

基本上你缺少 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')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python