0

在views.py中我的一个Django项目中,我有一些代码:

from django.shortcuts import render
from django.http import HttpResponse
from .models import *

# Create your views here.

products = Product.objects.all()
product_list = list(products)

def displayhome(request):
    return render(request, 'bootstrap/index.html', {'title': product_list[0].title}, {'link': product_list[0].official_path_name})

现在使用这个(非常笨拙)的方法,我可以使用以下方法将变量的字符串版本放入 html 中:

{{title}}

例如。但是,这不允许我对变量进行操作,例如,如果我通过发送,product_list我无法获取product_list[0]. 我隐约知道使用{% %}标签代替,{{ }}但我 (a) 不完全确定它们是如何工作的,并且 (b) 不知道它们有多强大,例如,如果你可以像使用普通的 python 文件一样使用它。

例如,我将如何使用来自 python 的变量(比如它是一个值为 4 的整数)来创建可变数量的 html 元素(例如 4 个框)?

如果没有简单的方法在 html 中执行 python,有没有办法将我的 python 变量放入 javascript,然后以某种方式在 html 中使用这些变量?

4

1 回答 1

2

我使用这个结构来表达我的观点:

def your_view(request):
    myResult = MODEL_NAME.objects.all()

    context = {
            "variable1":[0,1,2,3,4,5,6],
            "variable2":"This is the variable 2",
            "variable3":"This is the variable 3",
            "variable4":myResult
            }
    return render(request, 'your_html.html', context)

你可以像这样访问模板中的变量

<!-- See variables by index   -->
{{ variable1.0 }}
{{ variable1.2 }}

<!-- Iterate over variables -->
{% for x in variable1 %}
      {{ x }}
{% endfor %}

<!-- Variable 2 & 3 -->
{{ variable2 }}
{{ variable3 }}

<!-- Query set result -->
{% for x in variable4 %}
      {{ x.id }}
      {{ x.name }} <!-- and all the other values from your model -->
{% endfor %}

于 2021-09-01T23:53:11.727 回答