Django error: render_to_response() got an unexpected keyword argument 'context_instance'

前端 未结 3 1102
醉话见心
醉话见心 2020-12-05 22:35

After upgrading to Django 1.10, I get the error render_to_response() got an unexpected keyword argument \'context_instance\'.

My view is as follows:

相关标签:
3条回答
  • 2020-12-05 22:53

    Django 2.0.7 python 3.5

    in project/urls.py

    handler404 = 'project.views.not_found'
    handler500 = 'project.views.server_error'
    

    in 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 is passed because otherwise it throws TypeError: server_error() missing 1 required positional argument: 'exception'

    0 讨论(0)
  • 2020-12-05 23:02

    in Django 1.8 is compatible:

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

    in 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)
    
    0 讨论(0)
  • 2020-12-05 23:13

    The context_instance parameter in render_to_response was deprecated in Django 1.8, and removed in Django 1.10.

    The solution is to switch to the render shortcut, which automatically uses a RequestContext.

    Update your imports and view as follows. Note that render takes the request object as its first argument.

    from django.shortcuts import render
    
    def my_view(request):
        context = {'foo': 'bar'}
        return render(request, 'my_template.html', context)
    

    The render shortcut was introduced in Django 1.3, so this change is compatible with older versions of Django.

    0 讨论(0)
提交回复
热议问题