141👍
Use {{ request.user.get_profile.whatever }}
. Django’s templating language automatically calls things that are callable – in this case, the .get_profile()
method.
28👍
Not sure why it’s different for me, but I need to use {{user}} rather than {{request.user}}.
- [Django]-How do I make an auto increment integer field in Django?
- [Django]-Pulling data to the template from an external database with django
- [Django]-Django Model Field Default Based Off Another Field in Same Model
8👍
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.
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
- [Django]-Split models.py into several files
- [Django]-Filtering using viewsets in django rest framework
5👍
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: testuser03@auditor.com
Session Started at- April 16, 2018, 9:38 p.m.
Thanks 🙂
- [Django]-Django 1.7 – "No migrations to apply" when run migrate after makemigrations
- [Django]-Difference between filter with multiple arguments and chain filter in django
- [Django]-How to create an object for a Django model with a many to many field?
4👍
If you are using Django > 1.5 you can no longer use get_profile
.
If you have a legacy app, you should remove AUTH_PROFILE_MODULE = 'myapp.profile'
from your settings.py
.
If you use models.OneToOneField(User)
in your Profile class, you can simply use
{{ request.user.profile.whatever }}
in your Django template
- [Django]-Import data from excel spreadsheet to django model
- [Django]-Using django-rest-interface
- [Django]-Django ModelForm: What is save(commit=False) used for?
1👍
Working !
In your profile model provide related_name
user = models.OneToOneField(AUTH_USER_MODEL, related_name="user_profile", on_delete=models.CASCADE)
Then in template use. Here company_name is field in profile table
{{ request.user.user_profile.company_name }}
- [Django]-.filter() vs .get() for single object? (Django)
- [Django]-Django – Circular model import issue
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?