Django

Code

Changeset 5368

Show
Ignore:
Timestamp:
05/27/07 08:41:10 (1 year ago)
Author:
mtredinnick
Message:

Fixed #4221 -- Removed dependence on hard-coded URL in tutorial 4.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/tutorial04.txt

    r5366 r5368  
    4949    from django.shortcuts import get_object_or_404, render_to_response 
    5050    from django.http import HttpResponseRedirect 
     51    from django.core.urlresolvers import reverse 
    5152    from mysite.polls.models import Choice, Poll 
    5253    # ... 
     
    6768            # with POST data. This prevents data from being posted twice if a 
    6869            # user hits the Back button. 
    69             return HttpResponseRedirect('/polls/%s/results/' % p.id
     70            return HttpResponseRedirect(reverse('results', args=(p.id,))
    7071 
    7172This code includes a few things we haven't covered yet in this tutorial: 
     
    8788      ``HttpResponseRedirect`` rather than a normal ``HttpResponse``. 
    8889      ``HttpResponseRedirect`` takes a single argument: the URL to which the 
    89       user will be redirected. You should leave off the "http://" and domain 
    90       name if you can. That helps your app become portable across domains
     90      user will be redirected (see the following point for how we construct 
     91      the URL in this case)
    9192 
    9293      As the Python comment above points out, you should always return an 
    9394      ``HttpResponseRedirect`` after successfully dealing with POST data. This 
    9495      tip isn't specific to Django; it's just good Web development practice. 
     96 
     97    * We are using the ``reverse()`` function in the ``HttpResponseRedirect`` 
     98      constructor in this example. This function helps avoid having to 
     99      hardcode a URL in the view function. It is given the name of the view 
     100      that we want to pass control to and the variable portion of the URL 
     101      pattern that points to that view. In this case, using the URLConf we set 
     102      up in Tutorial 3, this ``reverse()`` call will return a string like :: 
     103 
     104        '/polls/3/results/' 
     105 
     106      ... where the ``3`` is the value of ``p.id``. This redirected URL will 
     107      then call the ``'results'`` view to display the final page. 
     108 
     109      For more information about ``reverse()``, see the `URL dispatcher`_ 
     110      documentation. 
    95111 
    96112As mentioned in Tutorial 3, ``request`` is a ``HTTPRequest`` object. For more 
     
    122138 
    123139.. _request and response documentation: ../request_response/ 
     140.. _URL dispatcher: ../url_dispatch#reverse 
    124141 
    125142Use generic views: Less code is better