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

标签 django model

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

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/

相关文章:

php - 让 HABTM 关系在 CakePHP 中独一无二

opengl - Assimp三角测量不起作用

django - 又不存在于/admin/login/---- 吗?

python - django 在 syncdb 时不加载初始固定装置

使用 kwargs 时的 Python 2 和 3 元类兼容性

r - R 模型矩阵中因子的所有级别

php - Codeigniter - 自动加载带有别名的模型

django - 使用 django-proxy 的示例?

python - django-redis 无效的数据库索引错误和 redis url 的含义

python - 如何将模型移动到 Django 站点管理中的其他部分