I have a form in my html:
<form id="form" action="" method="post"> {% csrf_token %}
<div>{{form.input1}}</div>
<div>{{form.input2}}</div>
<div>{{form.input3}}</div>
<input type="submit" class="btn" name="submit" value="submit">
</form>
and in my urls.py:
urlpatterns = [
url(r'^$', views.MyView.as_view(success_url='/'), name='index'),
]
and sometimes when I hit submit, the csrf token gets triggered and says csrf token missing or incorrect.
First of all how is this possible? The doc says:
This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
From what I see it's implemented correctly.
The error message further says
- Your browser is accepting cookies
it does
- The view function passes a request to the template's render method
According to the doc I have that.
- In the template there is a {%csrf_token%} template tag inside each POST form that targets an internal URL
it is indeed, but that's the whole point of having a csrf token right?
- If you are not using
CsrfViewMiddleware
, then you must usecsrf_protect
on any views that use thecsrf_token
template tag, as well as those that accept the POST data.
According to the doc this is activated by default.
So why does it trigger sometimes (very rarely)?