[Django]-Django ImportError: cannot import name 'render_to_response' from 'django.shortcuts'

100👍

The render_to_response shortcut was deprecated in Django 2.0, and is removed in Django 3.0. You can use the render shortcut instead, which was added way back in Django 1.3. The render shortcut works similarly to render_to_response, but takes request as its first argument. Change your view as follows:

from django.shortcuts import render

def index(request):
    context = {'foo': 'bar'}
    return render(request, 'index.html', context) 

In your view, you have context_instance=RequestContext(request) as the third argument. This was deprecated in Django 1.8, and does not work in Django 1.10+.

If you are using render_to_response without context_instance, then you can pass None as the request to the render shortcut. For example, if you have,

return render_to_response('index.html', context)

then the equivalent with render is:

return render(None, 'index.html', context)

Note that if you pass None as the first argument, then your template will be rendered without any context processors. That could make the rendering slightly faster, but it might lead to CSRF errors, and means that you won’t be able to access variables from the context processors (e.g. {{ request }} and {{ user }}) unless you explicitly add them to the context. I wouldn’t recommend using None like this unless you understand these consequences.

Leave a comment