加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 具有多个模型的Django模板

发布时间:2020-12-20 13:15:47 所属栏目:Python 来源:网络整理
导读:我有一个模板,我需要从多个模型中呈现信息.我的models.py看起来像这样: # models.pyfrom django.db import modelsclass foo(models.Model): ''' Foo content '''class bar(models.Model): ''' Bar content ''' 我还有一个文件views.py,我根据this Django do
我有一个模板,我需要从多个模型中呈现信息.我的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,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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读