I am new to python. Also new to Django. I am trying to execute an AJAX request and follow the instructions here . At first, the result of restoring the csrf cookie was always null, so I found a decorator method called security_csrf_cookie. The problem is that he is requesting a submission, and I don’t know what kind to transmit, and where I can get a link to it. The code is pretty 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 a cookie? I would not want to use the method described here because I do not want to manually process 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', )