我有一个基于函数的 View ,具有以下功能:
def foo(request, id):
args = {...}
return render(request, 'template_name.html', args)
我想将其转换为基于类的代码。请告诉我:
- 我应该使用什么 View (
TemplateView
)? - 我应该重写什么方法 (
render()
)?
基本上,问题是:使用基于类的方法,上面的代码应该是什么样子?
最佳答案
您需要使用TemplateView
并重写get_context_data()
方法:
class MyView(generic.TemplateView):
template_name = 'template_name.html'
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context.update({'key1': 'value1'})
return context
另请参阅:Adding extra context .
关于python - 在基于类的 View 中返回 template_name + args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24868432/