djangodjango-viewscsrf

rendering template with csrf token and template context


Currently I am rendering HTML views with the following syntax:

t = loader.get_template('sometemplate.html')
c = Context ({
    'title': title,
    'content': conent,
})
return HttpResponse(t.render(c))

I want to add a form with CSRF protection in my view. What should I change in my syntax so I can pass both context and the token to render view?

The Django docs show a different approach for rendering a view with CSRF token in it, but there is no additional context passed in these examples.

Thanks in advance!


Solution

  • Use RequestContext instead of Context? Also, you can just use render_to_response instead of returning a HttpResponse:

    from django.shortcuts import render_to_response
    from django.template import RequestContext
    
    return render_to_response('sometemplate.html', { 'title': title, 'content': content }, context_instance=RequestContext(request))