Django版本:2.2
今天在练习窗体的时候使用到了csrf验证,所以views中的函数也要修改,通过 Template 的 render方法调用,但是遇到了context must be a dict rather than RequestContext,事实上有一些资料中已经指出来了,不仅仅是 RequestContext,其实Context也不可以。
这是我出错的代码
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
import os
from myform import models
def post(request):
tem = get_template('post.html')
moods = models.Mood.objects.all()
message = '如果要张贴信息,那么每一个信息都要填写'
request_context = RequestContext(request, {'moods': moods, 'message': message})
html = tem.render(request_context)
# html = tem.render(locals())
return HttpResponse(html)
这样运行后会出现标题中的错误,查询网上的资料发现根本原因是*django.template.loader.loader.get_template(template_name)*返回的对象并不是 django.template.Template 对象。
##解决方法如下:
from django.shortcuts import render
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
import os
from myform import models
from django.template import Template
moods = models.Mood.objects.all()
message = '如果要张贴信息,那么每一个信息都要填写'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(BASE_DIR, 'templates\post.html'), encoding='utf-8') as fr:
template_string = fr.read()
# 不能用get_template方法,必须用原生的read方法
tem = Template(template_string)
request_context = RequestContext(request)
request_context.push(locals())
return HttpResponse(tem.render(request_context))
这样解决了csrf验证(在网页中也要加入{% csrf_token %})