【问题标题】:From Python function to Django template从 Python 函数到 Django 模板
【发布时间】: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


    【解决方案1】:

    您可以覆盖视图的get_context_data 方法以将额外的变量添加到您的上下文中

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Test'] = Question.objects.count()
        return context
    

    您还可以在不改变上下文的情况下计算问题的数量。你可以从查询集中得到它

    {{ test_details.count }}
    

    【讨论】:

    • 谢谢。为什么我们不能只使用 {{ Test }}?有没有一种通用的方法可以在视图中编写 Python 函数并在模板中调用它?
    • 视图作为“视图”添加到上下文中,因此您可以将函数称为{{ view.Test }}
    • 这个网站对于查看通用视图ccbv.co.uk/projects/Django/3.0/django.views.generic.list/…中可用的内容非常有用
    猜你喜欢
    • 2011-01-08
    • 2017-02-27
    • 2013-04-05
    • 2020-06-08
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多