Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'User' as foreign key in Django 1.5

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:

myapp.userprofile: 'user' has a relation with model User, which has either not been installed or is abstract.

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?

like image 573
supermario Avatar asked Oct 17 '13 17:10

supermario


People also ask

How do I create a ForeignKey in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

Does Django index foreign keys?

Django automatically creates an index for all models. ForeignKey columns.

How do I refer primary key in Django?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).


1 Answers

Exactly in Django 1.5 the AUTH_USER_MODEL setting was introduced, allowing using a custom user model with auth system.

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):

class UserProfile(models.Model):     user = models.ForeignKey(settings.AUTH_USER_MODEL) 
  • See docs for 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:

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()) 
like image 110
Anton Strogonoff Avatar answered Oct 01 '22 14:10

Anton Strogonoff