【问题标题】:Returning template_name + args in class-based views在基于类的视图中返回 template_name + args
【发布时间】:2023-03-02 23:55:01
【问题描述】:

我有一个基于函数的视图函数:

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

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

  1. 我应该使用什么视图 (TemplateView)?
  2. 我要覆盖什么方法 (render())?

基本上,问题是:上面的代码使用基于类的方法应该是什么样子?

【问题讨论】:

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


    【解决方案1】:

    您需要使用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

    【讨论】:

    • 非常感谢。这正是我想要的。
    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2015-11-04
    相关资源
    最近更新 更多