Nil*_*Kar 1 python django django-views
我对同一模型有两个列表视图,我想使用 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
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题吗?
除非模板名称取决于某些参数(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 contextRun Code Online (Sandbox Code Playgroud)
如果模板是动态解析的(如根据某些 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 contextRun Code Online (Sandbox Code Playgroud)
但正如您自己可能看到的那样,这更复杂,因此仅当模板名称取决于“上下文”时才应使用。
函数get_template[GitHub]将确定使用哪个模板。如果第一个模板不存在,则将尝试下一个模板,直到函数找到模板为止。
| 归档时间: |
|
| 查看次数: |
3101 次 |
| 最近记录: |