Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign Key to User model

I want to create a 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 at some tutorials, everything seems to be the same as in my model, and the problem with _meta is never mentioned.

like image 766
Meph Avatar asked Sep 05 '11 14:09

Meph


People also ask

How are foreign keys used in models?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table.

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.

How do I reference a user model in Django?

Referencing the User model Instead of referring to User directly, you should reference the user model using django. contrib. auth. get_user_model() .

What is Auth_user_model?

AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file. For this you need to create custom User Model by either subclassing AbstractUser or AbstractBaseUser.


2 Answers

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

like image 66
rgeber Avatar answered Oct 01 '22 00:10

rgeber


You just want:

from django.contrib.auth.models import User

class MyModel(models.Model):
    ...
    user = models.ForeignKey(User)
    ...
like image 30
Joe Avatar answered Sep 30 '22 23:09

Joe