Can't get user in template using django.contrib.auth - django

What am i doing wrong? I just want the username of the user. I am logged so i don't know why it's not working.
views.py
from django.contrib.auth.models import User
def check_user(request):
data = dict()
user = User.objects.all()
data['user'] = user
return render(request, 'check_user.html', data)
urls.py
url(r'^check_user/$', views.check_user, name='check_user'),
check_user.html
{{ request.user.is_authenticated }}
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
And i'm getting this:
CallableBool(True)
Welcome, new user. Please log in.
when i should get:
Welcome, admin. Thanks for logging in.
If i use: {% if request.user.is_authenticated %} instead of {% if user.is_authenticated %} i'm getting this:
Welcome, . Thanks for logging in.

Your problem is in your view, you don't need to create data['user']. Because in template, Django already pass the template variable {{ user }}.
So in your view remove this data dict, and keep the current context, without modification.
def check_user(request):
return render(request, 'check_user.html', {})
And your template will work. (don't need to change something)
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates

user is queryset object in your template, in other words it is list of users, not single user.
If you need current user use this:
{% if request.user.is_authenticated %}
<p>Welcome, {{ request.user.username }}. Thanks for logging in.</p>
instead of
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
UPDATE
As Wilfried said in his answer and comment, it is not good practice to override variable user in template. So if you need list of users in view it would be better to rename context variable to users:
users = User.objects.all()
data['users'] = users

Related

Django check if the user that is logged in is the user that created a record

I have a Django model that records the user who created a record. I want to display a button on a template only if the user logged in is the same as the user on the record.
I want to do something similar to:
{% if user.is_authenticated and (request.user.is_superuser or request.user == task.user) %}
where task is the record.
How can I do this?
You can't use parentheses in the {% if %} template tag. You can use the following check which is equivalent:
{% if user.is_authenticated and request.user.is_superuser or user.is_authenticated and request.user == task.user %}
You can then drop the first user.is_authenticated check, because only an authenticated user will be a superuser.
{% if user.is_authenticated and request.user.is_superuser or user.is_authenticated and request.user == task.user %}
You may also be able to drop the second user.is_authenticated check if all tasks have a user (since an anonymous user is never equal to a real user).
{% if request.user.is_superuser or request.user == task.user %}
Django discourages putting complicated logic in the template. In this case, you might be able to put the logic in a filter, and then your template would simplify to:
{% if task|display_button:request.user %}...{% endif %}

Django. How display only loggedin user comments?

I want display comments from loggedin user, I tried this:
{% for c in request.user.game.comment_set.all %}
....
{% endfor %}
but doesn't work.
#edit.
Example:
User1 have comment1, comment2, User2 have comment3.
so if I log in to User1 account, I want see only comment1, comment2
The easiest way is to find user's comments in view and then pass them into your template.
views.py
user_comments = Comment.objects.filter(user=request.user)
return render(request, 'your_template.html', {'comments': user_comments)
your_template.html
{% for comment in comments %}
{{ comment.message }}
{% endfor %}

Boolean check inside a for loop in a Django template

In a Django template I have the following for loop
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
Through this loop I am showing the user all the uploaded files of my app.
Now say that I want to show the user only the files he/she has uploaded.
I have the current user in the variable {{ request.user }}
and also I have the user who did the i-th upload in {{ document.who_upload }}
My question is how can I compare these two variables inside the loop to show only the uploads that have a who_upload field that of the current user?
For example I tried the syntax
{% if {{ request.user }} == {{ document.who_upload }} %}
{% endif %}
but it does not seem to work.
What is the proper syntax for this check?
Thank you !
This should get the job done:
{% if request.user.username == document.who_upload.username %}
{% endif %}
But you should consider performing this logic in your view. This is assuming you're not looping over the entire queryset anywhere else.
views.py
========
from django.shortcuts import render
from .models import Document
def documents(request):
queryset = Document.objects.filter(who_upload=request.user)
return render(request, 'document_list.html', {
'documents': queryset
})
A better option would be to compare the users' primary keys, instead of comparing user objects, which most definitely will be different.
{% if request.user.pk == document.who_upload.pk %}
<span>You uploaded this file</span>
{% endif %}

How to display other user's profile

Please, I am creating a web app, when a user log in, he/she can see other users, and can click on the user's username to view that user's profile. But I am finding it difficult to display other users profile except the currently logged in user. Kindly help me on how to go about this. I would prefer a function based view.
views
def profile(request, username):
context = {
'userprofile': User.objects.get(username=username),
}
return render_to_response('profile.html',context)
profile.html
Name: {{ userprofile.get_full_name }}
Username: {{ userprofile.username }}
urls
url(r'^/profile/(?P<username>\w+)/$', auth(profile), {}, name='chat_history')
what I don't know is how apply this url on a username. As in this:
home.html
{% if messages %}
{% for message in messages %}
{% if message.sender == user %}
<p> {{ message.sender }} >
{{ message.receiver }} : <br/>
{{ message.message }}
<sub>{{ message.creation_date }}</sub>
</p>
{% endif %}
{% endfor %}
{% else %}
{% trans 'No chat history of you and this user' %}
{% endif %}
Have got no idea what 'xxxxx' should be
Probably importing User model from django.contrib.auth and passing it to your views could help.

Django - Retrieve Unauthenticated User object

As the titles states, I have a need for users to retrieve User information of different users, whether or not they're authenticated.
I have a 'profile' template with some logic to either display static user information (for public) or editable user information (for the user it belongs to).
PROBLEM: The condition in my template is returning "true" - the User object appears to be authenticated BUT it's not. If I navigate from that page (profile) no user logged in.
I'm fairly new to Django. Am I not retrieving the User object correctly in my view.py?
views.py
def GetProfileById(request, userid):
try:
user = User.objects.get(pk=userid)
except User.DoesNotExist:
return HttpResponseRedirect('/')
try:
user_profile = user.get_profile()
except Exception:
return HttpResponseRedirect('/')
context = {'user': user, 'user_profile': user_profile}
return render_to_response('profile.html', context, context_instance=RequestContext(request))
profile.html
{% if user.is_authenticated %}
<form id="form-about" class="form-horizontal" action="{% url update-user-profile %}" method="POST">
{% csrf_token %}
<p>{{ about_form.first_name }}</p>
<p>{{ about_form.last_name }}</p>
<p>{{ about_form.birthday }}</p>
<p>{{ about_form.profession }}</p>
<button class="btn btn-primary" type="submit">Save</button>
</form>
{% else %}
<p><b>Name:</b> {{ user.first_name }} {{ user.last_name }}</p>
<p><b>DOB:</b> {{ user_profile.birthday }}</p>
<p><b>Profession:</b> {{ user_profile.profession }}</p>
<p><b>Member since:</b> {{ user.date_joined|date:'Y-M-d' }}</p>
<p><b>Last login:</b> {{ user.last_login|date:'Y-M-d # H:i' }}</p>
{% endif %}
It seems like, what you're trying to do is, if a user is currently logged in, you want to show a form that lets them update a profile.
So the problem is:
In your view, you're setting user to a User object from the database.
This object does not represent or contain information about whether the current user is logged in. It's just the record from the database.
You want to check request.user, which represents the User object for the user who requested the web page.
So in your template, change:
{% if user.is_authenticated %}
to:
{% if request.user.is_authenticated %}
I believe you're confusing user and request.user. The former is the user being displayed, the latter is the user that is currently logged in, or an AnonymousUser if no one is logged in.
You want to display that form if the user that is currently logged in and the user being displayed are the same, right? Then just change
{% if user.is_authenticated %}
To
{% ifequal user request.user %}