【发布时间】:2020-04-04 07:24:48
【问题描述】:
我正在尝试了解 Django 并了解如何在 Django 的模板中显示 Python 函数的结果。作为一个简单的例子,假设我有一个带有问题列表的模型,我想使用一个函数来返回问题的数量,并将这个结果显示在模板中。我该怎么做?
我尝试在下面这样做,但它不起作用!
提前致谢
models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
views.py
from django.shortcuts import render
from django_app import models
from django.views.generic import ListView
from django_app.models import Question
class TestListView(ListView):
model = Question
context_object_name = 'test_details'
def Test(self):
return Question.objects.count()
urls.py
from django.urls import path
from django_app import views
from django_app.views import TestListView
app_name = 'django_app'
urlpatterns = [
path('',TestListView.as_view(), name='Test'),
]
question_list.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for item in test_details %}
{{Test}}
{{item.question_text}}
{% endfor %}
</body>
</html>
【问题讨论】:
标签: python django python-3.x django-views django-templates