Reputation: 65
In Django, I am trying to get a list of all users. I use the following query:
users = User.objects.all().order_by('id')
I am able to get a list of all the users, but it outputs a list of all users, but only showing the current users credentials? If I have 20 users, it will show 20 users but only the information for the currently logged in user. For example, I want to see a table like:
User | Email
------------
User1 | [email protected]
User2 | [email protected]
User3 | [email protected]
But if the current user that is logged in is User1, It shows:
User | Email
------------
User1 | [email protected]
User1 | [email protected]
User1 | [email protected]
Or if User2 is logged in, it shows:
User | Email
------------
User2 | [email protected]
User2 | [email protected]
User2 | [email protected]
Here is my view.py:
def portal_users(request):
users = User.objects.all().order_by('id')
return render(request, 'portal/users.html', {"users": users})
templates
{% for users in users %}
<tr>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
{% endfor %}
Upvotes: 0
Views: 53
Reputation: 40995
Change your template to the following:
{% for user in users %}
<tr>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
{% endfor %}
You are referencing users
as opposed to user
.
Upvotes: 1
Reputation: 614
By default, the user
variable inside a template references the current user, that's why you are printing the current user instead of an item in the users
list. Now you may say "even if that is happening the for loop should overwrite the user
variable inside the loop" and you are right!, but in this case, your for loop is {% for users in users %}
, notice that you are using users
for the variable and the iterable, so your loop should be {% for user in users %}
.
Upvotes: 1