python – 具有多个模型的Django模板
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 具有多个模型的Django模板,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1541字,纯文字阅读大概需要3分钟。
内容图文
我有一个模板,我需要从多个模型中呈现信息.我的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'),
我的问题是,在模板页面/ 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模板全部内容,希望文章能够帮你解决python – 具有多个模型的Django模板所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。