Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a foreign key to the User table in Django?

I'm creating a new model called Tickets which I want to ensure always has a valid userID assigned to it.

I'm using AUTH_PROFILE_MODULE to setup the profile which also gives the error NameError: name 'User' is not defined when I try to run syndb.

How do I setup a foreign key to make sure this always is the case?

## tickets/models.py

class Ticket(models.Model):
    user = models.ForeignKey(User,)
    # More model stuff.



# accounts/models.py   

class UserProfile(models.Model):
     user = models.ForeignKey(User, unique=True)
like image 504
Brandon Helwig Avatar asked Feb 11 '10 13:02

Brandon Helwig


2 Answers

so the problem was I was missing an import on my models.

from django.contrib.auth.models import User
like image 72
Brandon Helwig Avatar answered Sep 30 '22 18:09

Brandon Helwig


For future reference, according to the official Django documentation, it is recommended to reference the User model like this:

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


class Article(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
like image 20
kas Avatar answered Sep 30 '22 19:09

kas