Reputation: 2403
I'm trying out this example. Whenever I try accessing dajax function it gives "no csrf or session cookie" error. How can I add csrf token in the javascript. I tried adding csrf token in the template and it didn't work.
Upvotes: 0
Views: 1344
Reputation: 3101
Maybe this will help: "CSRF token missing or incorrect" while post parameter via AJAX in Django
Upvotes: 1
Reputation: 12448
From django doc:
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before CsrfResponseMiddleware if that is being used, and before any view middleware that assume that CSRF attacks have been dealt with.) Alternatively, you can use the decorator django.views.decorators.csrf.csrf_protect on particular views you want to protect (see below).
In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL:
{% csrf_token %}
This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.
In the corresponding view functions, ensure that the 'django.core.context_processors.csrf' context processor is being used. Usually, this can be done in one of two ways:
3.1 Use RequestContext, which always uses 'django.core.context_processors.csrf' (no matter what your TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views or contrib apps, you are covered already, since these apps use RequestContext throughout.
3.2 Manually import and use the processor to generate the CSRF token and add it to the template context.
Upvotes: 1
Reputation: 11038
1) add 'django.middleware.csrf.CsrfViewMiddleware' to your middleware_classes in settings.py
2) after the tag in the template, use {% csrf_token %}
basically, that's it
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax here you can find out about javascript and ajax csrf tokens
Upvotes: 2