CSRF token not getting inserted into template

387 views Asked by At

I am Django 1.7 rendering a view using this code. Here I am rendering a html template called frame.html and passing context.

from django.template import Context
from django.template import Template
from django.shortcuts import render 
from django.http import HttpResponse

def frame(request):
    if request.GET.get('qid'):
        qid = request.GET['qid']
        displayQuestion = questions.objects.filter(questionSetId=qid)[0].Questions
        questionJSON = json.loads(displayQuestion)
        template = Template('frame.html')
        context = Context({'qid':qid,'questionData':questionJSON})
        return render(request,'frame.html',context)
    else:
        return views.products(request)

In my template frame.html there is a form and I am usinf {%csrf_token%} tag inside that. Here is the code.

<form action="/submit"  method="POST" id="responseform">
      {% csrf_token %}
      <input type="hidden" id="questionID" name="questionID" value="{{qid}}">
      <input type="hidden" id="studentResponse" name="responses" value="">
</form>

My problem is, despite using the csrf_token tag, I am getting an error message CSRF token missing or incorrect . Please check this error. Thanks

1

There are 1 answers

1
Daniel Roseman On BEST ANSWER

Why are you using the Context class? render constructs a RequestContext for you when passed a dict, and it's that which you need in order to run context processors including the one that inserts the CSRF token. Just drop that import and use a dict:

    context = {'qid':qid,'questionData':questionJSON}
    return render(request,'frame.html',context)

You don't need the Template class or the variable you get from it, either - again, render does all that for you, and you're not even passing that template variable anywhere.