views:

40

answers:

1

I'm using django's built-in contrib.auth module and have setup a foreign key relationship to a User for when a 'post' is added:

class Post(models.Model):
    owner = models.ForeignKey('User')
    # ... etc.

Now when it comes to actually adding the Post, I'm not sure what to supply in the owner field before calling save(). I expected something like an id in user's session but I noticed User does not have a user_id or id attribute. What data is it that I should be pulling from the user's authenticated session to populate the owner field with? I've tried to see what's going on in the database table but not too clued up on the sqlite setup yet.

Thanks for any help...

+3  A: 

You want to provide a "User" object. I.e. the same kind of thing you'd get from User.objects.get(pk=13).

If you're using the authentication components of Django, the user is also attached to the request object, and you can use it directly from within your view code:

request.user

If the user isn't authenticated, then Django will return an instance of django.contrib.auth.models.AnonymousUser. (per http://docs.djangoproject.com/en/dev/ref/request-response/#attributes)

heckj
I am using decorator @login_required before this so hopefully the user should always be authenticated. Quite different to what I know from PHP... thanks for the help.
Thomas Slater
That'll do it - all that's really needed is the 'django.contrib.auth' under INSTALLED_APPS in your settings file.
heckj