Search code examples
djangocsrfdjango-context

CSRF token not rendered if using Context({dict}) vs just {dict}


Does anyone know why the following renders my template ok:

c= {'render_form' : form }
return render(request, 'page1.html', c)

but the following does not render the csrf token:

c= Context({'render_form' : form}) 
return render(request, 'page1.html', c)

The template looks like this:

<form method="post">
    {% csrf_token %}
    {{ render_form }}
     <input type="submit" value="Submit" class='btn' id="submitbutton" name="_submit" />
</form>

I want to keep render() and I would like to avoid using locals().


Solution

  • Depends on your Django version, but the render method used to take two context related arguments, context and context_instance, the latter expects a Context or RequestContext object, the first a dictionary. The documentation has some specific deprecation details:

    https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#optional-arguments