自定义用户模型在外键中不起作用
Custom user model not working in foreign key
我创建了一个工作正常的自定义用户模型。
问题是当从外键访问用户时,它抛出我:
DETAIL: Key (author_id)=(51) is not present in table "auth_user".
我的自定义用户是 userauth,显然模型仍在寻找原始用户模型而不是自定义模型。
这是我所做的:
#settings.py
AUTH_USER_MODEL = 'userauth.UserAuth'
#models.py
from django.conf import settings
User = settings.AUTH_USER_MODEL
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
author = models.ForeignKey(User, null=True,blank=True,default=None)
#admin.py
class AdminPost(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if getattr(obj, 'author', None) is None:
obj.author = request.user
obj.save()
我会做这样的事情(不要费心分配变量):
models.py:
from django.conf import settings
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
# You don't need 'default=None'
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
我创建了一个工作正常的自定义用户模型。 问题是当从外键访问用户时,它抛出我:
DETAIL: Key (author_id)=(51) is not present in table "auth_user".
我的自定义用户是 userauth,显然模型仍在寻找原始用户模型而不是自定义模型。
这是我所做的:
#settings.py
AUTH_USER_MODEL = 'userauth.UserAuth'
#models.py
from django.conf import settings
User = settings.AUTH_USER_MODEL
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
author = models.ForeignKey(User, null=True,blank=True,default=None)
#admin.py
class AdminPost(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if getattr(obj, 'author', None) is None:
obj.author = request.user
obj.save()
我会做这样的事情(不要费心分配变量):
models.py:
from django.conf import settings
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
# You don't need 'default=None'
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)