我有一个模板,我需要从中呈现来自多个模型的信息。我的 models.py 看起来像这样:
# models.py
from django.db import models
class foo(models.Model):
''' Foo content '''
class bar(models.Model):
''' Bar content '''
我还有一个文件views.py,我根据this Django documentation写的和 the answer given here ,看起来像这样:
# 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
我在 urls.py 上的 urlpatterns 有以下对象:
url(r'^path$',views.MyView.as_view(), name = 'name'),
我的问题是,在模板 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
现在在您的模板中,您可以通过引用在 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>
关于python - 具有多个模型的 Django 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682846/