Django 1.11登录页面报错:context必须是dict而非RequestContext求助
解决Django 1.11中"context must be a dict rather than RequestContext"错误
嘿,我来帮你搞定这个登录页面的错误问题!
错误原因
你碰到的这个问题,是因为Django 1.11对render_to_response函数的参数要求变了——它现在不再接受RequestContext对象作为上下文参数,只认普通的Python字典。以前老版本里用RequestContext的写法,在1.11里已经行不通啦。
解决方案
方案1:用Django推荐的render函数(优先选这个!)
Django早就建议用django.shortcuts.render代替render_to_response了,它会自动帮你处理请求上下文,根本不用手动构建RequestContext,代码还更简洁。修改你的代码如下:
from django.contrib import auth from django.shortcuts import render # 把render_to_response换成render from django.http import HttpResponseRedirect # 记得补上这个导入 def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/index/') else: # 直接传字典就行,render会自动处理上下文 return render(request, 'login.html', {'error': '用户名或密码错误'})
方案2:非要用render_to_response的话(不推荐哦)
如果你确实想保留render_to_response,可以用context_instance参数传入RequestContext,不过这个参数在Django 1.8就已经被弃用了,1.11虽然还能跑,但后续版本可能会彻底移除,所以还是不建议这么写。示例代码给你参考:
from django.contrib import auth from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponseRedirect def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/index/') else: context = {'error': '用户名或密码错误'} # 用context_instance传入RequestContext,注意这是弃用写法 return render_to_response('login.html', context, context_instance=RequestContext(request))
为啥推荐用render?
- 省事儿:自动包含请求上下文,不用手动写
RequestContext - 规范:符合Django现代开发的标准,后续升级版本兼容性更好
- 少踩坑:不容易出现这种上下文类型不匹配的错误
内容的提问来源于stack exchange,提问作者naturlich
相关产品推荐
相关产品推荐

