Adding CSRF protection to simple comment forms in Django
I have blog comment forms in Django and I would like to know the following:
- Should I add CSRF to the forms?
- If I want to use the simple "render_comment_form" method, how do I add it?
- If I can't add it like that, what is t开发者_JS百科he 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:
- Yes! You should protect all your data that is sent by POST requests to the server against CSRF attacks.
- 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 thecsrf_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. - 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.
精彩评论