Django - Foreign Key to User model

若如初见. 提交于 2019-12-12 07:46:22

问题


I want to create new model, something like:

user_name = models.ForeignKey(u"Username", User),

but when I try to syncdb, I get this error message:

"AttributeError: 'unicode' object has no attribute '_meta'"

When I look on some tutorials, everything seems to be the same like in my model and problem with "_meta" is never mentioned.


回答1:


A safer way to do this is to use the AUTH_USER_MODEL from the settings file.

Example:

from django.db import models
from django.conf import settings

class Article(models.Model):
    headline = models.CharField(max_length=255)
    article = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

By default settings.AUTH_USER_MODEL refers to django.contrib.auth.models.User without requiring you to do anything.

The advantage of this approach is that your app will continue to work even if you use a custom user model without modification.

For more information on how to make use of custom user models check out this part of the Django docs




回答2:


You just want:

from django.contrib.auth.models import User

class MyModel(models.Model):
    ...
    user = models.ForeignKey(User)
    ...


来源:https://stackoverflow.com/questions/7309588/django-foreign-key-to-user-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!