Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用CBV在同一模板上渲染2个模型_Python_Django - Fatal编程技术网

Python 使用CBV在同一模板上渲染2个模型

Python 使用CBV在同一模板上渲染2个模型,python,django,Python,Django,我正在尝试使用模板/dashboard/home.html中的循环,使用基于类的视图来呈现两个不同的模型 让我们看看我的代码: 视图.py class DashboardListView(ListView): model = Links template_name = 'dashboard/home.html' class ContentListView(ListView): model = Dashboard template_name = 'dashboard/home.html'

我正在尝试使用模板/dashboard/home.html中的循环,使用基于类的视图来呈现两个不同的模型

让我们看看我的代码:

视图.py

class DashboardListView(ListView):
model = Links
template_name = 'dashboard/home.html' 

class ContentListView(ListView):
model = Dashboard
template_name = 'dashboard/home.html' 
首先,我想使用相同的ListView,但无法使用

Myhome.html

{% for dashboard in object_list %}  {{dashboard.content}}  {% endfor %}

{% for links in object_list %} {{links.content}} {% endfor %}
我想渲染这两个模型,但是我只能渲染一个,另一个对象列表将获取前一个对象的内容


感谢您的帮助

首先,您可以使用以下方法为对象列表指定不同的Mae:

context_object_name =‘links_list’
然后,您可以向扩展此方法的上下文添加不同的元素:

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    # Add in a QuerySet 
     context[‘dashboard_list’]= Dashboard.objects.all()

    return context

现在还不是很清楚。让我们假设我想从我的模型链接和仪表板2在home.html中呈现:根据您的回答,我应该这样做:“class DashboardListView(ListView):model=Links template_name='Dashboard/home.html'context_object_name='Links_list'def get_context_data(self,**kwargs):context=super()model@GaëtanGR确切地说,只需注意使用正确的缩进来定义get_context_数据。然后使用以下内容更新模板:{%用于仪表板中的仪表板\u列表%}和{%用于链接中的链接\u列表%}。基于类的视图自动获取第一个模型,然后在上下文中聚合第二个模型。上下文是传递给模板的dict。