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

Jam*_*Lin 12 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)
Run Code Online (Sandbox Code Playgroud)

并使用内置的UserAdmin

admin.site.register(User, UserAdmin)
Run Code Online (Sandbox Code Playgroud)

虽然编辑用户记录工作正常,但是当我添加用户时,我收到以下错误

Exception Value: 
relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
Run Code Online (Sandbox Code Playgroud)

Jam*_*Lin 28

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

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

罪魁祸首是一个函数clean_username里面UserCreationForm里面django.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'])
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试猴子修补原始UserCreationForm替换User变量.


San*_*min 5

这是由于迁移未运行.通过运行以下命令解决了此问题:

python manage.py syncdb


Ris*_*nha 5

Django 1.8

如果您的应用尚未使用迁移,那么这也可能是问题,因为contrib.auth使用它们.为我的应用启用迁移为我解决了这个问题.

$ ./manage.py makemigrations <my_app>
$ ./manage.py migrate
Run Code Online (Sandbox Code Playgroud)