Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use ensure_csrf_cookie?

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',
)
like image 317
Nicolás Straub Avatar asked Nov 21 '13 13:11

Nicolás Straub


4 Answers

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):
       ...
like image 58
Ryan Pergent Avatar answered Oct 05 '22 08:10

Ryan Pergent


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):
...
like image 44
Nikita Avatar answered Oct 05 '22 06:10

Nikita


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.

like image 26
H H H Avatar answered Oct 05 '22 08:10

H H H


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 ;)

like image 31
marxin Avatar answered Oct 05 '22 06:10

marxin