CSRF 令牌未插入到模板中
CSRF token not getting inserted into template
我是 Django 1.7 使用此代码渲染视图。我在这里渲染一个名为 frame.html
的 html 模板并传递上下文。
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
。请检查此错误。谢谢
为什么要使用上下文 class? render
在传递字典时为您构造一个 RequestContext,这是您 运行 上下文处理器(包括插入 CSRF 令牌的处理器)所需要的。只需删除该导入并使用字典:
context = {'qid':qid,'questionData':questionJSON}
return render(request,'frame.html',context)
您不需要模板 class 或您从中获得的变量 - 同样,render
会为您完成所有这些工作,您甚至不需要传递 template
变量在任何地方。
我是 Django 1.7 使用此代码渲染视图。我在这里渲染一个名为 frame.html
的 html 模板并传递上下文。
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
。请检查此错误。谢谢
为什么要使用上下文 class? render
在传递字典时为您构造一个 RequestContext,这是您 运行 上下文处理器(包括插入 CSRF 令牌的处理器)所需要的。只需删除该导入并使用字典:
context = {'qid':qid,'questionData':questionJSON}
return render(request,'frame.html',context)
您不需要模板 class 或您从中获得的变量 - 同样,render
会为您完成所有这些工作,您甚至不需要传递 template
变量在任何地方。