简体   繁体   中英

Adding CSRF protection to simple comment forms in Django

I have blog comment forms in Django and I would like to know the following:

  1. Should I add CSRF to the forms?
  2. If I want to use the simple "render_comment_form" method, how do I add it?
  3. If I can't add it like that, what is the best practice for doing it?

Each tutorial or discussion on the subject seems to have a different approach, and I am not certain I understand how it all works.

My answer assumes that you are using Django 1.2:

  1. Yes! You should protect all your data that is sent by POST requests to the server against CSRF attacks.
  2. You don't need to add the token yourself. This is already done by django. Have a look at the default template that is used by the render_comment_form tag and you will see, that the csrf_token is already included. You can overwrite this template in your project and including the CSRF token into it is as easy as writing {% csrf_token %} into the form.
  3. There is a way to protect your forms even if you don't set the tokens in the templates. Have a look at django's documentation about that topic . But this method is marked as a legacy method so it's not recommended to use that - it's only provided for backwards compatibility with versions of Django earlier than 1.2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM