Django中的通用ListView中的多个模板

dud*_*ein 2 django django-templates django-generic-views

我有一个对象列表,可以看作是一个单独的页面或另一个页面(虽然ajax).

所以,在我的模板中,我有一个"list_template.html",它只有列表本身,当我在另一个页面中查看列表时使用,以及"full_list_template.html",它扩展了基本模板并使用了"include"标签包含"list_template".

我想使用相同的URL来获取两种情况下的项目列表.我还使用通用ListView来显示对象列表.

几个问题:

1)在两种情况下使用相同的URL是一种好方法吗?

2)如果是,我怎样才能有一个与ListView相关联的URL并根据"请求"更改template_name参数?

小智 5

是的,您可以在两种情况下使用相同的URL,并通过检查值来设置相应的模板request.is_ajax().现在不使用template_nameclass属性,而是覆盖get_template_names()方法(此方法应返回模板列表,将使用找到的第一个模板):

class MyView(ListView):
    def get_template_names(self):
        if self.request.is_ajax():
            return ['list_template.html']
        return ['full_list_template.html']
Run Code Online (Sandbox Code Playgroud)