22👍
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.
19👍
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/
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-Python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"
- [Django]-How to send headers in Django rest framework browsable API
7👍
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:
- Use
request.user.get_username()
in views &user.get_username
in
templates. Preferred over referring username attribute directly.
Source - This template context variable is available if a RequestContext is used.
- django.contrib.auth.context_processors.auth is enabled by default & contains the variable user
- You do NOT need to enable django.core.context_processors.request template context processor.
Source : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
- [Django]-How does Django Know the Order to Render Form Fields?
- [Django]-TypeError: ManyRelatedManager object is not iterable
- [Django]-Django DateField default options
-1👍
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
- [Django]-How to make Django serve static files with Gunicorn?
- [Django]-How to render HTML in string with Javascript?
- [Django]-How do I use pagination with Django class based generic ListViews?