[Fixed]-How do I use ensure_csrf_cookie?

17👍

Cookies sets on server response, so you need to setup @ensure_csrf_cookie decorator for view, that renders page, from which user will make ajax-request.

On example, if users browser make ajax-request on sites main page, set this decorator for view, responsible for main page.

UPDATE: ajax request calls from sandbox page?
then try to set ensure_csrf_cookie for sandbox view, like this:

@ensure_csrf_cookie
def sandbox(request):
...
👤Nikita

28👍

For those looking for a way to do this with class based view:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie

class MyView(View):

    @method_decorator(ensure_csrf_cookie)
    def get(self, request, *args, **kwargs):
       ...

3👍

Although you have found what you were looking for these concepts will help you.

Views are functions that get called when a URL is requested. And there are two types of views:

  1. Function based views
  2. Class based views.

The basic working of view is to process a HttpRequest and send out a HttpResponse.
And every view that is returning a HttpResponse must have a request parameter.

Ex of a function based view:

def myView(request):
   ...
  # process the request here
   return HttpResponse() # or render_to_response depending upon what you want.

I dont see a request parameter in your view.

Now a decorator is something that puts certain conditions on a view.

For example: If you have view function for commenting and you want the user to be logged in to comment, then you can use a login_required decorator on the view.

This will ensure that anyone who wants to comment will first need to login. The basic syntax is:

@login_required   # this is the decorator
def comment(request):   # this is the view on which the decorator is acting upon
 ...
 ... 
 return HttpResponse()

Similar to the @login_required, @ensure_csrf_cookie is a decorator.

👤H H H

2👍

CSRF tokens are automatically validated when you have:

MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)

in your project settings.py file.

When you have such middleware, you need only to put crsf_token variable to all your forms (in templates), and it’s automatically validated, for example:

<form>
{% csrf_token %}
...

I don’t know if I understood your problem at all 😉

👤marxin

Leave a comment