-1

I have come to the frightning conclusion that it might not be possible to use ajax and django as far as the csrf protection is concerned:

def my_view(request):
    c = {}
    c.update(csrf(request))
    return render_to_response("a_template.html", c)

That's the example from django. However, if I do render_to_response, that will reload the page which makes ajax useless.

Is there a way to get around this?

Jenia Ivanov
  • 2,485
  • 3
  • 41
  • 69
  • It is doable. This post might help you get started: http://racingtadpole.com/blog/django-ajax-and-jquery/ – karthikr May 19 '14 at 15:06
  • thanks karthikr, i'm not using templates like in the example: {% csrf_token %}... I don't know how to set the csrf cookie without the template. – Jenia Ivanov May 19 '14 at 16:11
  • this is how you do it: stackoverflow.com/questions/3289860/… or also something like this: docs.djangoproject.com/en/dev/ref/contrib/csrf/… – Jenia Ivanov May 19 '14 at 22:09

1 Answers1

0

Your conclusion is completely incorrect.

The Django documentation gives a very good overview of how to use Ajax with CSRF. Your assertion that you need to use render_to_response is a red herring: that is one way of getting the value into the template, but as the docs say the canonical value is in the cookie. And anyway, it is quite possible to return an Ajax response via render_to_response (or, even better, render()) without refreshing the page: that is up to your Javascript.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • but who sets the cookie? isnt the cookie set here: c.update(csrf(request)) ? – Jenia Ivanov May 19 '14 at 15:47
  • No, not at all. That's simply for including it in the template context: if you're not using a template with a `{% csrf_token %}` call, it's irrelevant. As the docs say, the cookie is set automatically by the CSRF middleware: see [the source](https://github.com/django/django/blob/1.6/django/middleware/csrf.py#L197). – Daniel Roseman May 19 '14 at 15:57
  • i;m not calling django when i first render the page. it a static page and it calls django asynchronously as needed. Also, I have the csrf middleware enabled. When I tried to get the coolie using js, its missing, its not there. – Jenia Ivanov May 19 '14 at 16:09