Python 如何在 Django 1.5 中使用“用户”作为外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19433630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use 'User' as foreign key in Django 1.5
提问by supermario
I have made a custom profile model which looks like this:
我制作了一个自定义配置文件模型,如下所示:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey('User', unique=True)
name = models.CharField(max_length=30)
occupation = models.CharField(max_length=50)
city = models.CharField(max_length=30)
province = models.CharField(max_length=50)
sex = models.CharField(max_length=1)
But when I run manage.py syncdb
, I get:
但是当我运行时manage.py syncdb
,我得到:
myapp.userprofile: 'user' has a relation with model User, which has either not been installed or is abstract.
myapp.userprofile: 'user' 与模型 User 有关系,它要么没有安装,要么是抽象的。
I also tried:
我也试过:
from django.contrib.auth.models import BaseUserManager, AbstractUser
But it gives the same error. Where I'm wrong and how to fix this?
但它给出了同样的错误。我错在哪里以及如何解决这个问题?
采纳答案by Captain Skyhawk
Change this:
改变这个:
user = models.ForeignKey('User', unique=True)
to this:
对此:
user = models.ForeignKey(User, unique=True)
回答by Anton Strogonoff
Exactly in Django 1.5 the AUTH_USER_MODEL
setting was introduced, allowing using a custom user model with auth system.
正是在 Django 1.5中引入了该AUTH_USER_MODEL
设置,允许使用带有身份验证系统的自定义用户模型。
If you're writing an app that's intended to work with projects on Django 1.5 through 1.10 and later, this is the proper way to reference user model (which can now be different from django.contrib.auth.models.User
):
如果您正在编写一个旨在与 Django 1.5 到 1.10 及更高版本上的项目一起使用的应用程序,这是引用用户模型的正确方法(现在可以与 不同django.contrib.auth.models.User
):
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
- See docsfor more details.
- 有关更多详细信息,请参阅文档。
In case you're writing a reusable app supporting Django 1.4 as well, then you should probably determine what reference to use by checking Django version, perhaps like this:
如果您正在编写一个支持 Django 1.4 的可重用应用程序,那么您可能应该通过检查 Django 版本来确定要使用的引用,可能像这样:
import django
from django.conf import settings
from django.db import models
def get_user_model_fk_ref():
if django.VERSION[:2] >= (1, 5):
return settings.AUTH_USER_MODEL
else:
return 'auth.User'
class UserProfile(models.Model):
user = models.ForeignKey(get_user_model_fk_ref())