【问题标题】:Retrieving multiple items and displaying them on a website检索多个项目并将其显示在网站上
【发布时间】:2016-08-07 03:03:41
【问题描述】:

我正在尝试从 django 数据库中检索多条记录以显示在网页上的表格中。

这是我目前的代码...

class AdminView(TemplateView):
template_name = 'admin.html'
print("hello world")
def get(self, request):
    template = 'admin.html'
    data = str(Quiz.objects.all())
    admin = AdminForm(request.GET)
    context = {"admin": admin}
    context['data'] = data
    return render(request, template, context)

这是目前为止的网页...

{% if request.user.is_authenticated%}
{% if request.user.username  == "teacher"  %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        {% load staticfiles %}
        <meta charset="UTF-8">
        <title>Admin</title>
        <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
    </head>
    <body>
    {% include 'navbar.html' %}

    Admin Test

    {{ data }}

    </body>
    </html>
    {% endif %}
{% endif %}

{% if not request.user.is_authenticated %}
<h2>Login Required</h2>
{% endif %}

您认为这段代码有什么问题?如何让它显示 str?

【问题讨论】:

  • 这段代码有什么问题
  • 这段代码到底有什么问题。
  • Stack Overflow 用于帮助解决问题,而不是猜测它们是什么,您应该描述您要解决的问题。
  • 我正在尝试从 django 数据库中检索多条记录以显示在网页上的表格中。

标签: django django-models


【解决方案1】:

出于某种奇怪的原因,您尝试获取查询集的字符串表示形式

data = str(Quiz.objects.all())

你不需要,只需将数据设置到查询集

data = Quiz.objects.all()

然后遍历它们

{% for obj in data %}
    {{ obj }}
{% endfor %}

【讨论】:

  • 这仍然只是输出:Admin Test Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object Quiz object - 到网页。
  • @PhilipCrocker - 是的,obj 这是您的测验对象的一个​​实例,因此您需要决定要显示该对象的哪个部分
  • 这是这段代码输出的内容。我应该使用什么语法来显示对象的特定部分。
  • @PhilipCrocker - 与您用于检查用户用户名的语法类型相同。
  • 你的意思是 request.quiz.username 吗?
【解决方案2】:

要添加到 Sayse 回答的内容,例如,您可以执行以下操作:

{% for obj in data %}
    {{ obj.display }}
{% endfor %}

您的测验模型可能类似于:

class Quiz(models.Model):

    ...

    def display(self):
        return 'This will display on your page'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    相关资源
    最近更新 更多