views:

2046

answers:

3

I'm storing some additional per-user information using the AUTH_PROFILE_MODULE.

We can access the user in a Django template using {{ request.user }} but how do we access fields in the profile since the profile is only accessible via a function user.get_profile() ?

Is it really required to explicitly pass the profile into the template every time?

+18  A: 

Use {{ request.user.get_profile.whatever }}. Django's templating language automatically calls things that are callable - in this case, the .get_profile() method.

AdamKG
+1: Beat me by 3 seconds!
S.Lott
Very cool. Didn't know that it'll "call a callable" implicitly.
Swaroop C H
See http://docs.djangoproject.com/en/dev/topics/templates/#variables The rules are very cool.
S.Lott
+3  A: 

Yes it is possible to access profile from template using request.user.get_profile

However there is a small caveat: not all users will have profiles, which was in my case with admin users. So calling directly {{ request.user.get_profile.whatever }} from the template will cause an error in such cases.

If you are sure all your users always have profiles it is safe to call from template, otherwise call get_profile() from within try-except block in your view and pass it to the template.

it's try-except ;)
Vasil
:) yep, thanks, fixed it
+2  A: 

Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.

Rachel
The docs say (http://docs.djangoproject.com/en/dev/topics/auth/#authentication-data-in-templates) that you can access the user simply by {{user}}, as you say.
Xiong Chiamiov