Python - render with csrf protection

后端 未结 3 1020
醉话见心
醉话见心 2021-01-13 18:42

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.

The clearest

相关标签:
3条回答
  • 2021-01-13 19:21

    As far as I remember Django has its own middleware for the csrf protection that handles everthing transparently for you. Just include the {% csrf_token %} inside you forms. CSRF token is mandatory for POST requests (except you use the @csrf_exempt decorator). So a form would be:

    <form action="." method="post">
    {% csrf_token %}
     your input fields and submit button...
    </form>
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-13 19:24

    As long as you have the "django.middleware.csrf.CsrfViewMiddleware" listed in your MIDDLEWARE_CLASSES variable in the settings file you should be to just have {% csrf_token %} in your templates.

    There's a lot more useful info in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

    0 讨论(0)
  • 2021-01-13 19:28

    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.

    0 讨论(0)
提交回复
热议问题