gpt4 book ai didi

管理员中的 Django 自定义用户模型,关系 "auth_user"不存在

转载 作者:行者123 更新时间:2023-12-04 00:02:31 24 4
gpt4 key购买 nike

我有一个自定义用户模型,如下所示:

class User(AbstractUser):
subscribe_newsletters = models.BooleanField(default=True)
old_id = models.IntegerField(null=True, blank=True)
old_source = models.CharField(max_length=25, null=True, blank=True)

并使用内置的 UserAdmin
admin.site.register(User, UserAdmin)

虽然编辑用户记录工作正常,但是当我添加用户时,出现以下错误
Exception Value: 
relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...

最佳答案

经过一番挖掘,我发现了这个

https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms

罪魁祸首是函数clean_usernameUserCreationFormdjango.contrib.auth.forms.py .已经创建了一些票证,但显然维护者并不认为这是一个缺陷:

https://code.djangoproject.com/ticket/20188

https://code.djangoproject.com/ticket/20086

def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
User在此文件中直接引用内置用户模型。

为了解决这个问题,我创建了我的自定义表单
from models import User #you can use get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import forms

class MyUserCreationForm(UserCreationForm):
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])

class Meta(UserCreationForm.Meta):
model = User

class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm

admin.site.register(User,MyUserAdmin)

或者您可以尝试猴子修补原始 UserCreationForm替换 User多变的。

关于管理员中的 Django 自定义用户模型,关系 "auth_user"不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com