TheCoxer
TheCoxer

Reputation: 511

Creating a foreign key for user from one app to another in Django

I wanted to create a user foreign key in my tasks models.py to another table called UserProfile. I want a task to be associated to a user so when I go to query it and display it in a profile page, I don't see anyone else's. However, when I attempted this, I got this error:

enter image description here

This is my tasks.model.py

from django.db import models
from django.contrib.auth.models import User
from useraccounts.models import UserProfile

class Task(models.Model):
    task_name = models.CharField(max_length=140, unique=True)
    owner = models.ForeignKey('user')
    description = models.CharField(max_length=140)
    create_date = models.DateField()
    completed = models.BooleanField()
    private = models.BooleanField()

    def __unicode__(self):  # Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
        return self.name

This is my useraccounts.models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, default='')
    username = models.CharField(max_length=14, default='')
    birth_date = models.DateField(null=True, default = '2000-01-01', blank=True)
    email = models.EmailField(null=True, default='')

Upvotes: 0

Views: 1221

Answers (1)

cezar
cezar

Reputation: 12012

In your class Task you define the foreign key like this:

owner = models.ForeignKey('user')

This requires a class named user in the same app. And you don't have it.
Because you want to build a relation to a model from another app, you have to use the following pattern app_label.Model. In your case it should look like this:

owner = models.ForeignKey('useraccounts.UserProfile')

Upvotes: 1

Related Questions