python - /accounts/signup/ Manager 的 AttributeError 不可用;'auth.User' 已替换为 'accounts.CustomUser'
问题描述
我有一个自定义注册表单SignupForm
,用于检查email
自定义用户对象是否存在CustomUser
并引发一个ValidationError
if 存在。但是当我尝试提出错误时,我得到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"
我错过了什么?
解决方案
基本上你缺少 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')
推荐阅读
- r - 在 ggplot geom_bar 上更改填充变量的顺序
- python - 如何从现有字典列表创建嵌套字典
- discord - 将 DMed 文件和链接发送到服务器中的频道
- c - 如何正确访问字符串数组的单个字符?
- javascript - 如何使用打字稿在画布html中翻译六边形
- javascript - 带有文本溢出的 CSS 错误:Vuetify 列中的省略号
- r - 如何在 r studio 中制作直方图,但使用行值
- nuxt.js - xml2js + Nuxt,怎么用?
- javascript - 通过首先浏览 JavaScript 模块在 R 中进行 Web 抓取
- c# - 在我的 Asp .net 2.1 ADFS 实现中,我的帐户控制器中的 GetExternalLoginInfoAsync 始终返回 null