我有一个以以下内容开头的模板:
{% extends load_template %}
load_template在我看来是从这种条件中获取值的
if user == 'guest':
load_template = 'damage/menus/menu.html'
else:
load_template = 'damage/menus/sidebarmenu.html'
我使用generic.UpdateView进行更新(它返回错误,因为load_template变量没有值) 如何在此UpdateView中将值传递给此变量?
答案 0 :(得分:2)
您可以修补get_context_data
[Django-doc]:
from django.views.generic.detail import UpdateView
class MyUpdateView(UpdateView):
model = MyModel
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if somecondition:
load_template = 'damage/menus/menu.html'
else:
load_template = 'damage/menus/sidebarmenu.html'
context['load_template'] = load_template
return context
因此,这会将一个名为load_template
的变量添加到上下文中。请注意,此处未定义user
。登录的用户是self.request.user
。例如:
from django.views.generic.detail import UpdateView
class MyUpdateView(UpdateView):
model = MyModel
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if not request.user.is_authenticated:
load_template = 'damage/menus/menu.html'
else:
load_template = 'damage/menus/sidebarmenu.html'
context['load_template'] = load_template
return context