How can I display all the users on my html page?

This piece of code gets me the required output in my python terminal

views.py

from django.contrib.auth.models import User

userList =User.objects.all()
print(userList)

outputs this in the terminal

<QuerySet [<User: brad>, <User: john>]>

I know I have to iterate through the QuerySet but I am not able to link this view to my main page.

So how can I get this on my main HTML page?

Upvotes: 0

Views: 906

Answers (2)

user8193706
user8193706

Reputation: 2425

In your views.py create view as

from django.views.generic.list import ListView
from django.contrib.auth.models import User

class UserListView(ListView):

    model = User
    template_name = 'your_template_name.html'

Then in your urls.py

from django.urls import path
from yourapp.views import UserListView

urlpatterns = [
    path('userlists', UserListView.as_view(), name='user-list'),
]

Then in your html loop through object_list as

<h1>User List</h1>
<ul>
{% for user in object_list %}
    <li>{{ user.username }}</li>
{% empty %}
    <li>No users yet.</li>
{% endfor %}
</ul>

Upvotes: 1

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

Here is pseudo code you can try,

from django.contrib.auth.models import User
from django.shortcuts import render

def index(request):
    userList =User.objects.all()
    return render(request, 'users.html', {'users': userList})

And users.html like,

<h1>USERS</h1>
<ul>
{% for user in users %}
    <li>{{ user }}</li>
{% endfor %}
</ul>

urls.py is like,

from django.contrib import admin
from django.urls import path
from app1.views import *

urlpatterns = [
    path('', index),
    path('admin/', admin.site.urls),
]

Upvotes: 0

Related Questions