Python-使用CSRF保护进行渲染 [英] Python - render with csrf protection
问题描述
我已经阅读了几篇有关Django中的csrf保护的文章,包括 Django的文档,但是在如何正确使用它方面我还是很困惑。
I've read several posts about csrf protection in Django, including Django's documentation , but I'm still quite confused in how to use it correctly.
最清晰的部分是HTML,而Python的部分令人困惑。
The clearest part is the HTML one, but the Python's one is kinda confusing.
{%csrf_token%}
格式
c = {}
c.update(csrf(request))
在显示和请求信息时,您需要以各种形式使用它,不是吗?
You need it in every form when displaying and requesting the information, don't you?
然后,如何在返回中包含此csrf保护render()
?
返回渲染(请求,'index.html',{'var':var_value})
还是我应该在 Python文档示例(返回render_to_response( a_template.html ,c)
)。或者,如果正确,它是否包含在请求
变量中?
or should I include the c
somewhere like in the Python documentation example (return render_to_response("a_template.html", c)
). Or, if it's correct, is it included in the request
var?
而且,由于我没有任何形式,不需要使用csrf时。
And, when not needing to use csrf because I don't have any form. Would this be the right form to return values to a template?
return render(request,'index.html',{'var': var_value})
推荐答案
使用渲染器$的要点c $ c>快捷方式是它然后自动运行所有上下文处理器。上下文处理器是有用的小功能,每次渲染模板时,它们都会向模板上下文中添加各种内容。并且有一个内置的上下文处理器已经为您添加了CSRF令牌。因此,如果您使用
render
,则除了在模板中输出令牌外,无需执行其他操作。
The point of using the render
shortcut is that it then runs all the context processors automatically. Context processors are useful little functions that add various things to the template context every time a template is rendered. And there is a built-in context processor that already adds the CSRF token for you. So, if you use render
, there is nothing more to do other than to output the token in the template.
这篇关于Python-使用CSRF保护进行渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!