UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.

3,272 views
Skip to first unread message

huw_at1

unread,
Nov 19, 2013, 7:45:27 AM11/19/13
to django...@googlegroups.com
Hi there,

I'm trying to get to the bottom of this warning that I am getting:

/usr/local/lib/python2.7/site-packages/django/template/defaulttags.py:59: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.
  warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")

My setup is that I have a form that I am passing to my views via AJAX. I prepare the AJAX POST following the guidelines at:


I am then returning the response using:

return HttpResponse(json.dumps(data), content_type="application/json")

The data returned in the response is then used to update the template that also includes the form.

From the warning I guess I am not returning the CSRF token in the response? Is that the issue? I did try adding the @ensure_csrf_cookie decorator to the views function but still got this warning. Should I manually return a RequestContext and modify my javascript to handle the token accordingly? Apologies - it's the first time I've done anything like this...

Many thanks for any help or light anyone can shed on this.

Giulio Calacoci

unread,
Nov 19, 2013, 8:51:55 AM11/19/13
to django...@googlegroups.com
Il 19/11/2013 13:45, huw_at1 ha scritto:
{% csrf_token %}
If you are using the ajax metod, you don't need this tag in the form template.

According with the documentation, you set the csrf token using javascript in the beforeSend part of the javascript code.


Hope I've correctly understood your problem.

Regards.

Giulio

-- 
 Giulio Calacoci - 2ndQuadrant Italia
 PostgreSQL Training, Services and Support
 giulio....@2ndQuadrant.it | www.2ndQuadrant.it 
Message has been deleted

huw_at1

unread,
Nov 19, 2013, 9:04:14 AM11/19/13
to django...@googlegroups.com
Hi,

Many thanks. There is another form in the page which does contain this {% csrf_token %} tag. Removing this does remove the warning so this is indeed the issue. I just need to write the other form out of the template.

Thanks for the answer :)
Reply all
Reply to author
Forward
0 new messages