17

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.

Shawn Chin
  • 74,316
  • 17
  • 152
  • 184
Meph
  • 514
  • 1
  • 6
  • 14
  • 1
    I finaly found out. It was my stupid mistake. I had in my another model: class Meta: verbose_name = smart_encode(u"something). Sorry about that and thank You both! – Meph Sep 05 '11 at 16:12

2 Answers2

36

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

rgeber
  • 501
  • 4
  • 6
  • is it possible to restrict the foreign key? so what if I only want the foreign key to relate to a group of users? – OverflowingTheGlass Jan 31 '18 at 20:53
  • 1
    @CameronTaylor Yes, that is possible. Use [`limit_choices_to`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) to restrict the choice to certain group of users. – cezar Aug 23 '18 at 10:02
26

You just want:

from django.contrib.auth.models import User

class MyModel(models.Model):
    ...
    user = models.ForeignKey(User)
    ...
syntagma
  • 20,485
  • 13
  • 66
  • 121
Joe
  • 42,600
  • 24
  • 134
  • 225