how do I use ensure_csrf_cookie?
csrf, django, django-views, python
Solution
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):
...
Problem
I'm new to python. Also new to Django. I'm trying to make an AJAX request and followed the instructions here. at first, the result of retrieving the csrf cookie was always null, so I found a decorator method called ensure_csrf_cookie. The problem is it asks for a view, and I've no idea what view to pass and where I can get a reference to it. The code is quite simple: ``` from django.shortcuts import render_to_response from django.core.context_processors import csrf from django.views.decorators.csrf import ensure_csrf_cookie def csv_to_xform(csv, template): return render_to_response(template, { "data": "it works!" }) ``` Do I need to use a class based view? if so, is there a better way to set the cookie? I'd like not to use the method described here, because I don't want to have to manually handle the value. The rest of the code is as follows: sandbox.html: ``` <!doctype html> <html> <head> <title>Sandbox</title> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script src="/static/js/csrf.js"></script> <script type="text/javascript"> $(function () { $('#send-csv-btn').click(function () { $.post('/csv', { data: '1, 2, 3', success: function (response) { console.debug(response); }, error: function (response) { console.debug(response); } }); }); }); </script> </head> <body> <form> {% csrf_token %} <input type="button" id="send-csv-btn" /> </form> </body> </html> ``` urls.py: ``` urlpatterns = patterns('', url(r'^$', 'dkobo.formbuilder.views.main', name='fb'), url(r'^admin/', include(admin.site.urls)), url(r'^csv$', 'dkobo.formbuilder.views.csv_to_xform', { "template": "sandbox-stub.html" }), url(r'^sandbox$', 'dkobo.formbuilder.views.sandbox') ) ``` settings.py: ``` MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ```