How to access the user profile in a Django template?
Use {{ request.user.get_profile.whatever }}
. Django's templating language automatically calls things that are callable - in this case, the .get_profile()
method.
Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.
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.
If it helps anyone, I used the followings in my template:
Username: {{ user.username }}
User Full name: {{ user.get_full_name }}
User Group: {{ user.groups.all.0 }}
Email: {{ user.email }}
Session Started at: {{ user.last_login }}
A sample result is like this:
User: auditor ezio
User Group: auditGroup
Username: testUser03
Email: [email protected]
Session Started at- April 16, 2018, 9:38 p.m.
Thanks :)