This repository has been archived by the owner. It is now read-only.
Permalink
Browse files

replace render_to_response with render

Replaced the render_to_response shortcut with render everywhere because
newer django code tends not to use render_to_response at all. Also
updated text where it refered to render_to_response arguments and the
use of RequestContext with render.
  • Loading branch information...
RaphaelKimmig committed Oct 20, 2012
1 parent c1cb41f commit a4724d5cc5aa0357fd67de0248792770ff85387a
Showing with 91 additions and 89 deletions.
  1. +1 −1 appendixG.rst
  2. +2 −2 chapter01.rst
  3. +15 −15 chapter04.rst
  4. +4 −4 chapter05.rst
  5. +21 −21 chapter07.rst
  6. +21 −21 chapter08.rst
  7. +13 −11 chapter09.rst
  8. +11 −11 chapter14.rst
  9. +1 −1 chapter15.rst
  10. +2 −2 chapter20.rst
View
@@ -463,7 +463,7 @@ Here's an example::
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
- return render_to_response('polls/detail.html', {'poll': p})
+ return render(request, 'polls/detail.html', {'poll': p})
In order to use the ``Http404`` exception to its fullest, you should create a
template that is displayed when a 404 error is raised. This template should be
View
@@ -132,12 +132,12 @@ an HTML template (``latest_books.html``)::
# views.py (the business logic)
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
from models import Book
def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
- return render_to_response('latest_books.html', {'book_list': book_list})
+ return render(request, 'latest_books.html', {'book_list': book_list})
# urls.py (the URL configuration)
View
@@ -1252,7 +1252,7 @@ directory using the following template code::
Refresh the page in your Web browser, and you should see the fully rendered
page.
-render_to_response()
+render()
--------------------
We've shown you how to load a template, fill a ``Context`` and return an
@@ -1263,39 +1263,39 @@ things. Because this is such a common idiom, Django provides a shortcut that
lets you load a template, render it and return an ``HttpResponse`` -- all in
one line of code.
-This shortcut is a function called ``render_to_response()``, which lives in the
+This shortcut is a function called ``render()``, which lives in the
module ``django.shortcuts``. Most of the time, you'll be using
-``render_to_response()`` rather than loading templates and creating ``Context``
+``render()`` rather than loading templates and creating ``Context``
and ``HttpResponse`` objects manually -- unless your employer judges your work
by total lines of code written, that is.
Here's the ongoing ``current_datetime`` example rewritten to use
-``render_to_response()``::
+``render()``::
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
import datetime
def current_datetime(request):
now = datetime.datetime.now()
- return render_to_response('current_datetime.html', {'current_date': now})
+ return render(request, 'current_datetime.html', {'current_date': now})
What a difference! Let's step through the code changes:
* We no longer have to import ``get_template``, ``Template``, ``Context``,
or ``HttpResponse``. Instead, we import
- ``django.shortcuts.render_to_response``. The ``import datetime`` remains.
+ ``django.shortcuts.render``. The ``import datetime`` remains.
* Within the ``current_datetime`` function, we still calculate ``now``, but
the template loading, context creation, template rendering, and
``HttpResponse`` creation are all taken care of by the
- ``render_to_response()`` call. Because ``render_to_response()`` returns
+ ``render()`` call. Because ``render()`` returns
an ``HttpResponse`` object, we can simply ``return`` that value in the
view.
-The first argument to ``render_to_response()`` is the name of the template to
-use. The second argument, if given, should be a dictionary to use in creating a
-``Context`` for that template. If you don't provide a second argument,
-``render_to_response()`` will use an empty dictionary.
+The first argument to ``render()`` is the request, the second is the name of
+the template to use. The third argument, if given, should be a dictionary to
+use in creating a ``Context`` for that template. If you don't provide a third
+argument, ``render()`` will use an empty dictionary.
Subdirectories in get_template()
--------------------------------
@@ -1312,11 +1312,11 @@ the subdirectory name and a slash before the template name, like so::
t = get_template('dateapp/current_datetime.html')
-Because ``render_to_response()`` is a small wrapper around ``get_template()``,
-you can do the same thing with the first argument to ``render_to_response()``,
+Because ``render()`` is a small wrapper around ``get_template()``,
+you can do the same thing with the second argument to ``render()``,
like this::
- return render_to_response('dateapp/current_datetime.html', {'current_date': now})
+ return render(request, 'dateapp/current_datetime.html', {'current_date': now})
There's no limit to the depth of your subdirectory tree. Feel free to use
as many subdirectories as you like.
View
@@ -41,7 +41,7 @@ In this example view, we use the ``MySQLdb`` library (available via
http://www.djangoproject.com/r/python-mysql/) to connect to a MySQL database,
retrieve some records, and feed them to a template for display as a Web page::
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
import MySQLdb
def book_list(request):
@@ -50,7 +50,7 @@ retrieve some records, and feed them to a template for display as a Web page::
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
db.close()
- return render_to_response('book_list.html', {'names': names})
+ return render(request, 'book_list.html', {'names': names})
.. SL Tested ok
@@ -77,12 +77,12 @@ As you might expect, Django's database layer aims to solve these problems.
Here's a sneak preview of how the previous view can be rewritten using Django's
database API::
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
from mysite.books.models import Book
def book_list(request):
books = Book.objects.order_by('name')
- return render_to_response('book_list.html', {'books': books})
+ return render(request, 'book_list.html', {'books': books})
We'll explain this code a little later in the chapter. For now, just get a
feel for how it looks.
View
@@ -162,10 +162,10 @@ Generally, there are two parts to developing a form: the HTML user interface
and the backend view code that processes the submitted data. The first part is
easy; let's just set up a view that displays a search form::
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
def search_form(request):
- return render_to_response('search_form.html')
+ return render(request, 'search_form.html')
As we learned in Chapter 3, this view can live anywhere on your Python path.
For sake of argument, put it in ``books/views.py``.
@@ -278,14 +278,14 @@ Now that we've verified ``request.GET`` is being passed in properly, let's hook
the user's search query into our book database (again, in ``views.py``)::
from django.http import HttpResponse
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
from mysite.books.models import Book
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
- return render_to_response('search_results.html',
+ return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
@@ -349,20 +349,20 @@ render the template again, like this:
.. parsed-literal::
from django.http import HttpResponse
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
from mysite.books.models import Book
def search_form(request):
- return render_to_response('search_form.html')
+ return render(request, 'search_form.html')
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
- return render_to_response('search_results.html',
+ return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
- **return render_to_response('search_form.html', {'error': True})**
+ **return render(request, 'search_form.html', {'error': True})**
(Note that we've included ``search_form()`` here so you can see both views in
one place.)
@@ -411,9 +411,9 @@ parameters::
error = True
else:
books = Book.objects.filter(title__icontains=q)
- return render_to_response('search_results.html',
+ return render(request, 'search_results.html',
{'books': books, 'query': q})
- return render_to_response('search_form.html',
+ return render(request, 'search_form.html',
{'error': error})
.. SL Tested ok
@@ -487,9 +487,9 @@ like this:
**error = True**
else:
books = Book.objects.filter(title__icontains=q)
- return render_to_response('search_results.html',
+ return render(request, 'search_results.html',
{'books': books, 'query': q})
- return render_to_response('search_form.html',
+ return render(request, 'search_form.html',
{'error': error})
Now, if you try submitting a search query greater than 20 characters long,
@@ -537,9 +537,9 @@ how we might fix that:
**errors.append('Please enter at most 20 characters.')**
else:
books = Book.objects.filter(title__icontains=q)
- return render_to_response('search_results.html',
+ return render(request, 'search_results.html',
{'books': books, 'query': q})
- return render_to_response('search_form.html',
+ return render(request, 'search_form.html',
{**'errors': errors**})
Then, we need make a small tweak to the ``search_form.html`` template to
@@ -623,7 +623,7 @@ this::
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
def contact(request):
errors = []
@@ -642,7 +642,7 @@ this::
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
- return render_to_response('contact_form.html',
+ return render(request, 'contact_form.html',
{'errors': errors})
.. SL Tested ok (modulo email config and lack of thanks view)
@@ -696,7 +696,7 @@ A couple of new things are happening here:
``HttpResponseRedirect`` object. We'll leave the implementation of that
"success" page up to you (it's a simple view/URLconf/template), but we
should explain why we initiate a redirect instead of, for example, simply
- calling ``render_to_response()`` with a template right there.
+ calling ``render()`` with a template right there.
The reason: if a user hits "Refresh" on a page that was loaded via
``POST``, that request will be repeated. This can often lead to undesired
@@ -740,7 +740,7 @@ edit each HTML field to insert the proper value in the proper place:
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
- return render_to_response('contact_form.html', {
+ return render(request, 'contact_form.html', {
'errors': errors,
**'subject': request.POST.get('subject', ''),**
**'message': request.POST.get('message', ''),**
@@ -957,7 +957,7 @@ Here's how we can rewrite ``contact()`` to use the forms framework::
# views.py
- from django.shortcuts import render_to_response
+ from django.shortcuts import render
from mysite.contact.forms import ContactForm
def contact(request):
@@ -974,7 +974,7 @@ Here's how we can rewrite ``contact()`` to use the forms framework::
return HttpResponseRedirect('/contact/thanks/')
else:
form = ContactForm()
- return render_to_response('contact_form.html', {'form': form})
+ return render(request, 'contact_form.html', {'form': form})
# contact_form.html
@@ -1081,7 +1081,7 @@ hurt.) To do this, we can use the ``initial`` argument when we create a
form = ContactForm(
**initial={'subject': 'I love your site!'}**
)
- return render_to_response('contact_form.html', {'form': form})
+ return render(request, 'contact_form.html', {'form': form})
.. SL Tested ok
Oops, something went wrong.

0 comments on commit a4724d5

Please sign in to comment.