Using Django auth User model as a Foreignkey and reverse relations


I am using the User model from django.contrib.auth.models. I have another model called Post which references User through a foreign key.

The problem is when I try to access a logged in user's posts through


I get an error, User object has no attribute post_set. So how do I use the default auth model with foreign keys?

3/28/2011 11:32:14 AM

Have you included the application containing the Post model in your installed apps?


    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',

and ran syncdb?

python syncdb

i.e does the database table for the Post model definately exist?

I did a quick test and found no problems:

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

class PostModel(models.Model):
    user = models.ForeignKey(User)

(test) C:\Users\Steven\django_projects\test\testproj>python shell
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.contrib.auth.models import User
>>> test = User.objects.get(username='test')
>>> test.postmodel_set.all()
3/28/2011 6:26:41 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow