我正在尝试从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?
答案 0 :(得分:1)
由于某些奇怪的原因,您试图获取查询集的字符串表示
data = str(Quiz.objects.all())
您不需要,只需将数据设置为查询集
data = Quiz.objects.all()
然后迭代它们
{% for obj in data %}
{{ obj }}
{% endfor %}
答案 1 :(得分:1)
To add to what Sayse answered you could, for example, do something like:
{% for obj in data %}
{{ obj.display }}
{% endfor %}
Your Quiz model might be something like:
class Quiz(models.Model):
...
def display(self):
return 'This will display on your page'