只在模板中使用forloop。
{% for r in result %}
{{ r.name }} {{ r.Type }}
{% endfor %}
用view 更新了答案
您的result 来自context。
基本上,django view 将数据渲染到您自己的模板。 context_processors 为你做这件事,它在 settings.py (TEMPLATES - OPTIONS - context_processors) 中定义。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(ROOT_DIR.path('templates')),
],
# 'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# you can add your own processors
'your_app.path.to.custom_processors',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
这里有更多关于context (official django docs)的详细信息
这就是您可以在模板中使用request、user 和其他上下文数据的原因。
如果您想在所有模板中使用上下文,您可以添加自己的context_processors。但在很多时候,您只需要特定模板中的上下文。 (比如你的情况)。
然后您可以将数据添加到上下文中,在您的 views 中。
如果您使用基于类的视图(我建议使用 CBV),您可以通过 get_context_data() 添加。像这样。
class ProductView(ListView):
model = Product
template_name = 'best.html'
context_object_name = 'products'
def get_context_data(self, **kwargs):
context = super(ProductView, self).get_context_data(**kwargs)
context['test'] = 'test context data'
return context
您可以在现有的context 中添加自己的上下文数据。
如果您使用 FBV,您可以使用您的上下文渲染模板。有很多渲染方法(render、render_to_response 等等。你可以查看 django 文档。我想你应该使用 render,因为 render_to_response 在 django 2.0 中已弃用)
from django.shortcuts import render
def my_view(request):
# View code here...
context = {'test': 'test coooontext data' }
return render(request, 'myapp/index.html', context)
通过在视图中传递您自己的上下文数据,您可以在模板中使用它。
因此,如果您只想传递“名称”和“类型”,则可以只传递您想要使用的数据,而不是全部。在视图中工作比在模板中更有效。我希望它有所帮助。