Joã*_*ias 5 python django django-templates jinja2
我有一个模板,我需要从中呈现来自多个模型的信息。我的 models.py 看起来像这样:
# models.py
from django.db import models
class foo(models.Model):
''' Foo content '''
class bar(models.Model):
''' Bar content '''
Run Code Online (Sandbox Code Playgroud)
我还有一个文件 views.py,我根据这个 Django 文档和这里给出的答案从中编写,看起来像这样:
# views.py
from django.views.generic import ListView
from app.models import *
class MyView(ListView):
context_object_name = 'name'
template_name = 'page/path.html'
queryset = foo.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['bar'] = bar.objects.all()
return context
Run Code Online (Sandbox Code Playgroud)
我在 urls.py 上的 urlpatterns 有以下对象:
url(r'^path$',views.MyView.as_view(), name = 'name'),
Run Code Online (Sandbox Code Playgroud)
我的问题是,在模板 page/path.html 上,如何从 foo 和 bar 引用对象和对象属性以在我的页面中显示它们?
要从您的模板访问 foos,您必须将其包含在上下文中:
# views.py
from django.views.generic import ListView
from app.models import *
class MyView(ListView):
context_object_name = 'name'
template_name = 'page/path.html'
queryset = foo.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['bars'] = bar.objects.all()
context['foos'] = self.queryset
return context
Run Code Online (Sandbox Code Playgroud)
现在,在您的模板中,您可以通过引用您在中创建上下文字典时使用的键来访问该值get_context_data:
<html>
<head>
<title>My pathpage!</title>
</head>
<body>
<h1>Foos!</h1>
<ul>
{% for foo in foos %}
<li>{{ foo.property1 }}</li>
{% endfor %}
</ul>
<h1>Bars!</h1>
<ul>
{% for bar in bars %}
<li>{{ bar.property1 }}</li>
{% endfor %}
</ul>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4278 次 |
| 最近记录: |