gpt4 book ai didi

python - Django 手动渲染表单并使用 csrf token

转载 作者:行者123 更新时间:2023-12-04 10:06:41 26 4
gpt4 key购买 nike

我想我正在慢慢掌握 Django 的窍门,但在编程方面相对较新且自学。我一直在模板中使用 form.as_p 和 form_ul,但想更好地了解如何使它们看起来更好。我查看了有关如何手动呈现表单的 Django 文档。这似乎像宣传的那样工作,我可以在我的 html 页面上显示各个字段等。但是在文档中突出显示了这一点:

Forms and Cross Site Request Forgery protection Django ships with an easy-to-use protection against Cross Site Request Forgeries. When submitting a form via POST with CSRF protection enabled you must use the csrf_token template tag as in the preceding example. However, since CSRF protection is not directly tied to forms in templates, this tag is omitted from the following examples in this document.



我想我不明白最后一行是什么意思。我认为这意味着我可以呈现我想要的所有表单,但除非发出 Post 请求,否则我不需要 CSRF token 。

是否有一个如何使用发布请求和 CSRF token 手动呈现表单的示例?

我还假设当我在 html 中编写表单时,由于它们不与模型和数据库交互,因此不需要 CSRF?那是因为关注的漏洞通常是将不需要的东西注入(inject)数据库吗?

我查看了其他一些 Django CSRF 文档,对如何需要中间件来实现 CSRF 保护有了一些了解,但我认为它假定了一些比我拥有的更详细的背景知识。任何关于阅读以了解更多信息以更好地理解 POST 和 CSRF 的建议,我猜是 cookie 等。

最佳答案

I assume it means that I can render the form all I want, but unless there is a Post request being made I don't need a CSRF token.



是的,PUT 和 POST 请求需要 CSRF token 。 GET 请求不需要它。但是您不应该使用 GET 来发送表单数据。

CSRF token 不是表单的属性。应用程序使用此 token 来验证来自客户端的请求。

Is there an example of how to manually render forms with post requests and CSRF tokens?



docs 中所述, 这很简单。
<form action="{% url "submit-form-url-name" %}" method="post" accept-charset="utf-8">
{% csrf_token %}
{{ form.field1 }}
{{ form.field2 }}
...
</form>

Is that because the vulnerability of concern is usually injecting something unwanted into the database?



CSRF token 是在服务器端生成的。它附加到用户的 session 并用于验证用户请求。如果用户正在向服务器发送一些表单数据,目的是将该数据保存在数据库/文件/缓存中,那么验证该请求是否真的仅来自有效用户是一个很好的做法。

...got a little bit of an idea of how the middleware is needed to implement CSRF protection...



Django 提供了一个默认的 CSRF 中间件,它非常易于配置和使用。
请注意,CSRF 不再是 OWASP 十大安全问题。它曾经虽然更早。

关于python - Django 手动渲染表单并使用 csrf token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61553433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com