views:

262

answers:

2

I'm using django-registration to log users into my application. That part works fine. The part that I cannot figure out is how to set custom session variables when the user logs in. For instance, I'd like to populate variables containing UserProfile data as well as the output of a few other functions. Then I'd be able to use that information in subsequent views/templates.

If anybody can point me to a tutorial online or post some sample code, that would be great.

I'm using django 1.1 and Python 2.6

A: 

If you don't want persistent storage of user data (just additional session data) have a look at:

http://docs.djangoproject.com/en/dev/topics/http/sessions/

The sessions framework will most probably be already enabled if you use django.contrib.auth.

If you want persistent storage of additional user data (not only in a session, but in the database), you will store them in another "profile" model:

http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

stefanw
I'm just looking for additional session data at this point. I already have all of the information in the database, just need to figure out how to get to it. I guess my real question is how can I set this session data while using django-registration? Is it possible or should I be writing my own function to log users in?
doza
You don't need to get profile data into the session. When using django.contrib.auth you can access the current user with request.user.
stefanw
Of course! I didn't think about it that way. That makes much more sense.Thanks!
doza
A: 

I realize @stefanw provided you an alternative solution, but to answer the original question:

Setting session data at login is difficult because the easiest place to set that data is in your view function, and the particular view function you'd want to modify is a part of the contrib.django.auth app.

So your options would be the following:

  • Create a small middleware class to set your session data.
  • Create a template tag or other bit of code than can be integrated into the login template or subsequent page that will set the data you want.
  • Write your own custom login view function (it's really quite easy, actually).

Happy django-ing!

Gabriel Hurley