Reputation: 3525
How can i get the current user in a django template tags? (request object is not accessible) Or how can i access to request object?
Upvotes: 22
Views: 33621
Reputation: 385
Suppose you have a profile page of every registered user, and you only want to show the edit link to the owner of the profile page (i.e., if the current user is accessing his/her profile page, the user can see the edit button, but the user can't see the edit button on other user's profile page. In your html file:
<h2>Profile of {{ object.username }}</h2>
{% if object.username == user.username %}
<a href="{% url 'profile_update' object.pk %}">Edit</a>
{% endif %}
Then your urls.py file should contain:
from django.urls import path
from .views import ProfileUpdateView
urlpatterns = [
...
path('<int:pk>/profile/update', ProfileUpdateView.as_view(), name = 'profile_update'),
...
]
considering you have appropriate ProfileUpdateView
and appropriate model
Upvotes: -1
Reputation: 1613
This question was already answered here:
{% if user.is_authenticated %}
<p> Welcome '{{ user.username }}'</p>
{% else %}
<a href="{% url django.contrib.auth.login %}">Login</a>
{% endif %}
and make sure you have the request template context processor installed in your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)
Note:
request.user.get_username()
in views & user.get_username
in
templates. Preferred over referring username attribute directly.
SourceSource : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
Upvotes: 7
Reputation: 19578
The user is always attached to the request, in your templates you can do the following:
{% if user.is_authenticated %}
{% endif %}
You don't have to specify "request" to access its content
UPDATE:
Be aware: is_authenticated()
always return True
for logged user (User
objects), but returns False
for AnonymousUser
(guest users). Read here: https://docs.djangoproject.com/en/1.7/ref/contrib/auth/
Upvotes: 20
Reputation: 3800
If you want to access the current user in a template tag, you must pass it as a parameter in the templates, like so:
{% my_template_tag user %}
Then make sure your template tag accepts this extra parameter. Check out the documentation on this topic. You should also check out simple tags.
Upvotes: 23