首页 > 解决方案 > 将 Django Admin 站点中的用户添加到网页上的 html 表中

问题描述

我正在尝试捕获 Django-Admin 站点中的用户数据并将其转换为 html 表。我遇到的问题是我的表只显示一个用户,即登录的用户。我想显示 Django Admin 数据库中所有用户的名称(类似于篮球花名册) . 我怎样才能做到这一点?谢谢你。

这是我的views.py代码:

from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from home.forms import HomeForm
from django.contrib.auth.decorators import login_required
from home.models import Post


class HomeView(TemplateView):
    template_name = 'home/home.html'


    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-created')
        users = User.objects.exclude(id=request.user.id).exclude(is_superuser=True)

        args = {'form': form, 'posts': posts, 'users': users}
        return render(request, self.template_name, args)

这是html模板代码:

  <table class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Player Name</th>
                    <th scope="col">Position</th>
                    <th scope="col">Grade</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th scope="row">{{ user.userprofile.jersey_number }}</th>
                    <td>{{ user.get_full_name }}</td>
                    <td>{{ user.userprofile.position }}</td>
                    <td>{{ user.userprofile.grade }}</td>

                </tr>
            </tbody>

我的输出

标签: pythonhtmldjango

解决方案


您的模板中没有任何类型的 for 循环,因此它自然只会显示一个用户。您需要遍历users从视图传递的集合。

{% for user in users %}
    <tr>
        <th scope="row">{{ user.userprofile.jersey_number }}</th>
        <td>{{ user.get_full_name }}</td>
        <td>{{ user.userprofile.position }}</td>
        <td>{{ user.userprofile.grade }}</td>
    </tr>
{% endfor %}

推荐阅读