I have a form:
<form action="{% url "some_url" %}" method="post">
{% csrf_token %}
<input type="text">Text Input
<button type="submit">Submit</button>
</form>
Which is being submitted via AJAX:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function (response) {
console.log(response);
});
});
});
The URL routes to this view:
class SomeView(View):
def post(self, request, *args, **kwargs):
context = dict(**some_data)
rendered_html = render_to_string('some_template.html', context, RequestContext(self.request))
return JsonResponse(dict(html=rendered_html))
All this works. The problem is that it also works when the CSRF token is not sent, I am getting the exact same successful response:
$.post($(this).attr('action'), function (response) {
console.log(response);
});
I would expect some kind of error to be raised because the CSRF token is missing.
To state the obvious: CsrfViewMiddleware
is within MIDDLEWARE_CLASSES
.
Explicitly using csrf_token
has the same result when the token is not sent:
method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
return super(SomeView, self).dispatch(request, *args, **kwargs)
What can I do to enforce its verification?
@dabadaba maybe the CSRF token is sent in cookie. So no matter what you post the cookies will be sent to the server. Read here for more details: https://docs.djangoproject.com/en/2.1/ref/csrf/