升级到Django 1.10后,我收到错误render_to_response() got an unexpected keyword argument 'context_instance'
。
我的观点如下:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view(request):
context = {'foo': 'bar'}
return render_to_response('my_template.html', context, context_instance=RequestContext(request))
以下是完整的追溯:
Traceback:
File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/alasdair/dev/rtr/rtr/urls.py" in my_view
26. return render_to_response('my_template.html', context, context_instance=RequestContext(request))
Exception Type: TypeError at /
Exception Value: render_to_response() got an unexpected keyword argument 'context_instance'
答案 0 :(得分:119)
context_instance
中的render_to_response
参数为deprecated in Django 1.8,并在Django 1.10中删除。
解决方案是切换到render
快捷方式,该快捷方式会自动使用RequestContext
。
更新您的导入并按如下方式查看。请注意,render
将request
对象作为其第一个参数。
from django.shortcuts import render
def my_view(request):
context = {'foo': 'bar'}
return render(request, 'my_template.html', context)
Django 1.3中引入了render
快捷方式,因此此更改与旧版本的Django兼容。
答案 1 :(得分:1)
Django 2.0.7 python 3.5
在project / urls.py
中handler404 = 'project.views.not_found'
handler500 = 'project.views.server_error'
在project / views.py
中def not_found(request, exception=None):
response = render(request, '404.html', {})
response.status_code = 404
return response
def server_error(request, exception=None):
response = render(request, '500.html', {})
response.status_code = 500
return response
exception = None不通过,因为否则会抛出 TypeError:server_error()缺少1个必需的位置参数:'exception'
答案 2 :(得分:0)
兼容:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view(request):
context = {'foo': 'bar'}
return render_to_response('my_template.html', {'context':context}, context_instance=RequestContext(request))
在Django 1.11中
from django.shortcuts import render
from django.template import RequestContext
def my_view(request):
context = {'foo': 'bar'}
return render(request, 'my_template.html', context)