【问题标题】:rendering template with csrf token and template context使用 csrf 令牌和模板上下文渲染模板
【发布时间】:2011-07-14 00:57:51
【问题描述】:

目前我正在使用以下语法呈现 HTML 视图:

t = loader.get_template('sometemplate.html')
c = Context ({
    'title': title,
    'content': conent,
})
return HttpResponse(t.render(c))

我想在我的视图中添加一个具有 CSRF 保护的表单。我应该在我的语法中进行哪些更改,以便我可以同时传递上下文和令牌来呈现视图?

Django docs 显示了一种不同的方法来呈现带有 CSRF 令牌的视图,但这些示例中没有传递额外的上下文。

提前致谢!

【问题讨论】:

    标签: django django-views csrf


    【解决方案1】:

    使用 RequestContext 代替 Context?此外,您可以只使用 render_to_response 而不是返回 HttpResponse:

    from django.shortcuts import render_to_response
    from django.template import RequestContext
    
    return render_to_response('sometemplate.html', { 'title': title, 'content': content }, context_instance=RequestContext(request))
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 1970-01-01
      • 2014-12-23
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 2018-11-25
      相关资源
      最近更新 更多