我为同一模型有两个列表视图,我想使用get_template_names()函数为一个视图指定模板,但是无法解析如何执行此操作...
这是我的两个视图:
class bloglistview(LoginRequiredMixin,ListView):
model = Blog
def get_queryset(self):
return Blog.objects.filter(User=self.request.user).order_by('id')
def get_context_data(self, **kwargs):
context = super(bloglistview, self).get_context_data(**kwargs)
context['categories_list'] = categories.objects.all()
return context
class allbloglistview(LoginRequiredMixin,ListView):
model = Blog
def get_queryset(self):
return Blog.objects.all().order_by('id')
def get_context_data(self, **kwargs):
context = super(allbloglistview, self).get_context_data(**kwargs)
context['categories_list'] = categories.objects.all()
return context
有人可以帮我吗?
最佳答案
除非模板名称取决于某些参数(URL参数,GET
参数,POST
参数,COOKIES
等),否则您只能指定template_name
属性,例如:
class bloglistview(LoginRequiredMixin,ListView):
model = Blog
template_name = 'my_fancy_template.hmtl'
def get_queryset(self):
return Blog.objects.filter(User=self.request.user).order_by('id')
def get_context_data(self, **kwargs):
context = super(bloglistview, self).get_context_data(**kwargs)
context['categories_list'] = categories.objects.all()
return context
如果模板是动态解析的(取决于某些URL参数或其他参数),则可以覆盖
get_template_names
函数,该函数应返回字符串列表:按该顺序搜索的模板名称。例如:class bloglistview(LoginRequiredMixin,ListView):
model = Blog
def get_template_names(self):
if self.request.COOKIES.get('mom'): # a certain check
return ['true_template.html']
else:
return ['first_template.html', 'second_template.html']
def get_queryset(self):
return Blog.objects.filter(User=self.request.user).order_by('id')
def get_context_data(self, **kwargs):
context = super(bloglistview, self).get_context_data(**kwargs)
context['categories_list'] = categories.objects.all()
return context
但是,正如您可能看到的那样,这更加复杂,因此仅当模板名称取决于“上下文”时才应使用。
get_template
function [GitHub]将确定要使用的模板。如果第一个模板不存在,则将尝试下一个模板,直到函数找到模板为止。关于python - 如何在CBV中实现get_template_names()函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52387438/