python - 在基于类的 View 中返回 template_name + args

标签 python django django-templates django-views django-class-based-views

我有一个基于函数的 View ,具有以下功能:

def foo(request, id):
  args = {...}
  return render(request, 'template_name.html', args)

我想将其转换为基于类的代码。请告诉我:

  1. 我应该使用什么 View (TemplateView)?
  2. 我应该重写什么方法 (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/

相关文章:

python - 不支持带有编码声明的 XML Unicode 字符串

带有 pydoc 的 django.views.generic 的 Python 文档

django - 如何在 Django 中测试自定义模板标签?

python - 我可以将图像上传到特定目录,但无法在模板中查看它们(找不到页面(404))

python - django 模板条件 html

python - 如何获取 AAD 用户的 GraphUserPrincipalNameCreationContext?

Python - 对 numpy.random 函数的调用线程安全吗?

python - beautifulsoup中属性为中文时如何获取标签

python - Django 1.8.3 网址

django - 在 Python 中限制文件的生命周期