Django doesn't work {% csrf token %}

Welcome. I've already broken my head. Does not want to work in any way {% csrf_token %}. Using Django v2. 0. 1, Added 'django.middleware.csrf.CsrfViewMiddleware' to the very beginning of MIDDLEWARE. In the template I draw like this:

<form class="..." action="" method="post">{% csrf_token %}

I render the template like this: return render_to_response( 'index.html', { }, ) And I tried it like that: return render( request, 'index.html', {} ) There are no decorators on the views. When you click button type= "submit", there is a script that sends an ajax request. And here, when you click, I get 403

(CSRF validation error. The request was rejected. CSRF cookie not set. )

No matter how hard I try to find a solution, the hidden field with the csrf key is not created in the form.

Maybe someone knows what the problem may be and will tell you ?

Author: Genome, 2018-01-23

1 answers

There is not enough context, usually this error occurs due to old examples and textbooks. The recommended shorthand function for template output is render().

If HttpResponse is used, then you need to pass context.

It is necessary in order to correctly work out the built-in tags, because otherwise nothing is known about them.

So many render functions are needed for different development and optimization options. If you do not need a template, then you do not need and trigger template engine processing, save on resources, improve performance.

There are also a lot of outdated functions and examples, so always use the documentation for the version you are working with, otherwise you will spend a few days because you no longer need quotes or the order has changed.

 1
Author: Igor, 2018-01-23 23:10:21