2015-06-21 42 views
0

我是Django 1.7使用此代碼呈現視圖。在這裏,我正在渲染一個名爲frame.html的html模板並傳遞上下文。CSRF令牌沒有插入到模板中

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) 

在我的模板frame.html有一個形式,我usinf內部的{%csrf_token%}標籤。這是代碼。

<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> 

我的問題是,儘管使用csrf_token標籤,我收到一條錯誤消息CSRF token missing or incorrect。請檢查這個錯誤。謝謝

回答

1

你爲什麼使用Context類? render在傳遞字典時會爲您構造一個RequestContext,並且它是運行上下文處理器(包括插入CSRF標記的處理器)所需的。剛落即進口和使用的字典:

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

你不需要模板類或變量,你從它那裏得到,要麼 - 再次,render做一切,對於你,你甚至不傳球那template變量在任何地方。

+0

我的無知,只有我的無知。真棒! – nitroman