Python Django模板呈现问题
我是python新手,但根据Java的经验,我对MVC有了相当的了解。 我的视图中有以下python代码Python Django模板呈现问题,python,django,model-view-controller,django-templates,Python,Django,Model View Controller,Django Templates,我是python新手,但根据Java的经验,我对MVC有了相当的了解。 我的视图中有以下python代码 from django.http import HttpResponse from django.template.loader import render_to_string class MyListClass: def __init__(self, link, text): self.link = link self.text = text
from django.http import HttpResponse
from django.template.loader import render_to_string
class MyListClass:
def __init__(self, link, text):
self.link = link
self.text = text
def index(request):
list1 = MyListClass("hi","_hi_")
list2 = MyListClass("hello","_hello_")
bullets = [list1,list2]
return HttpResponse(render_to_string("nest.html"), {"bullets": bullets})
以及HTML模板中的以下代码段
{% for bullet in bullets %}
<h2>
<a href="{{ bullet.link }}">
{{ bullet.text }}
</a>
</h2>
{% endfor %}
{%用于项目符号中的项目符号%}
{%endfor%}
但是这些值不会在html中发布,而其他静态文本则是从html中呈现的。
根据,传递的对象必须是命令式的。
如果我在某个地方出错,请告诉我。虽然您的代码应该可以工作(假设您将上下文传递给您发现的正确方法),但通常使用
render
方法,而不是直接构建HttpResponse
from django.shortcuts import render
def index(request):
bullets = [
MyListClass("hi", "_hi_"),
MyListClass("hello", "_hello_")
]
return render(request, "index.html", {"bullets": bullets})
我发现了问题。在python代码中,字典被传递到错误的方法。