Django

Code

Changeset 678

Show
Ignore:
Timestamp:
09/23/05 17:50:05 (3 years ago)
Author:
adrian
Message:

Changed overview and tutorial docs to use render_to_response and get_object_or_404, to cut down on code

Files:

Legend:

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

    r621 r678  
    196196article_detail from above:: 
    197197 
    198     from django.models.news import articles 
    199  
    200198    def article_detail(request, year, month, article_id): 
    201199        # Use the Django API to find an object matching the URL criteria. 
    202         try: 
    203             a = articles.get_object(pub_date__year=year, pub_date__month=month, pk=article_id) 
    204         except articles.ArticleDoesNotExist: 
    205             raise Http404 
    206         t = template_loader.get_template('news/article_detail') 
    207         c = Context(request, { 
    208             'article': a, 
    209         }) 
    210         content = t.render(c) 
    211         return HttpResponse(content) 
     200        a = get_object_or_404(articles, pub_date__year=year, pub_date__month=month, pk=article_id) 
     201        return render_to_response('news/article_detail', {'article': a}) 
    212202 
    213203This example uses Django's template system, which has several key features. 
     
    261251 
    262252Here's what the "base" template might look like:: 
    263  
    264253 
    265254    <html> 
  • django/trunk/docs/tutorial03.txt

    r602 r678  
    193193 
    194194    from django.core import template_loader 
    195     from django.core.extensions import DjangoContext as Context 
     195    from django.core.template import Context 
    196196    from django.models.polls import polls 
    197197    from django.utils.httpwrappers import HttpResponse 
     
    200200        latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5) 
    201201        t = template_loader.get_template('polls/index') 
    202         c = Context(request,
     202        c = Context(
    203203            'latest_poll_list': latest_poll_list, 
    204204        }) 
     
    243243containing the "What's up" poll from Tutorial 1. 
    244244 
     245A shortcut: render_to_response() 
     246-------------------------------- 
     247 
     248It's a very common idiom to load a template, fill a context and return an 
     249``HttpResponse`` object with the result of the rendered template. Django 
     250provides a shortcut. Here's the full ``index()`` view, rewritten:: 
     251 
     252    from django.core.extensions import render_to_response 
     253    from django.models.polls import polls 
     254 
     255    def index(request): 
     256        latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5) 
     257        return render_to_response('polls/index', {'latest_poll_list': latest_poll_list}) 
     258 
     259Note that we no longer need to import ``template_loader``, ``Context`` or 
     260``HttpResponse``. 
     261 
     262The ``render_to_response()`` function takes a template name as its first 
     263argument and a dictionary as its optional second argument. It returns an 
     264``HttpResponse`` object of the given template rendered with the given context. 
     265 
    245266Raising 404 
    246267=========== 
     
    255276        except polls.PollDoesNotExist: 
    256277            raise Http404 
    257         t = template_loader.get_template('polls/detail') 
    258         c = Context(request, { 
    259             'poll': p, 
    260         }) 
    261         return HttpResponse(t.render(c)) 
     278        return render_to_response('polls/detail', {'poll': p}) 
    262279 
    263280The new concept here: The view raises the ``django.core.exceptions.Http404`` 
    264281exception if a poll with the requested ID doesn't exist. 
     282 
     283A shortcut: get_object_or_404() 
     284------------------------------- 
     285 
     286It's a very common idiom to use ``get_object()`` and raise ``Http404`` if the 
     287object doesn't exist. Django provides a shortcut. Here's the ``detail()`` view, 
     288rewritten: 
     289 
     290    from django.core.extensions import get_object_or_404 
     291    def detail(request, poll_id): 
     292        p = get_object_or_404(polls, pk=poll_id) 
     293        return render_to_response('polls/detail', {'poll': p}) 
     294 
     295The ``get_object_or_404()`` function takes a Django model module as its first 
     296argument and an arbitrary number of keyword arguments, which it passes to the 
     297module's ``get_object()`` function. It raises ``Http404`` if the object doesn't 
     298exist. 
     299 
     300.. admonition:: Philosophy 
     301 
     302    Why do we use a helper function ``get_object_or_404()`` instead of 
     303    automatically catching the ``*DoesNotExist`` exceptions at a higher level, 
     304    or having the model API raise ``Http404`` instead of ``*DoesNotExist``? 
     305 
     306    Because that would couple the model layer to the view layer. One of the 
     307    foremost design goals of Django is to maintain loose coupling. 
     308 
     309There's also a ``get_list_or_404()`` function, which works just as 
     310``get_object_or_404()`` -- except using ``get_list()`` instead of 
     311``get_object()``. It raises ``Http404`` if the list is empty. 
    265312 
    266313Write a 404 (page not found) view 
  • django/trunk/docs/tutorial04.txt

    r603 r678  
    4949So let's create a ``vote()`` function in ``myproject/apps/polls/views/polls.py``:: 
    5050 
    51     from django.core import template_loader 
    52     from django.core.extensions import DjangoContext as Context 
     51    from django.core.extensions import get_object_or_404, render_to_response 
    5352    from django.models.polls import choices, polls 
    54     from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect 
    55     from django.core.exceptions import Http404 
     53    from django.utils.httpwrappers import HttpResponseRedirect 
    5654 
    5755    def vote(request, poll_id): 
    58         try: 
    59             p = polls.get_object(pk=poll_id) 
    60         except polls.PollDoesNotExist: 
    61             raise Http404 
     56        p = get_object_or_404(polls, pk=poll_id) 
    6257        try: 
    6358            selected_choice = p.get_choice(pk=request.POST['choice']) 
    6459        except (KeyError, choices.ChoiceDoesNotExist): 
    6560            # Redisplay the poll voting form. 
    66             t = template_loader.get_template('polls/detail') 
    67             c = Context(request, { 
     61            return render_to_response('polls/detail', { 
    6862                'poll': p, 
    6963                'error_message': "You didn't select a choice.", 
    7064            }) 
    71             return HttpResponse(t.render(c)) 
    7265        else: 
    7366            selected_choice.votes += 1 
     
    110103 
    111104    def results(request, poll_id): 
    112         try: 
    113             p = polls.get_object(pk=poll_id) 
    114         except polls.PollDoesNotExist: 
    115             raise Http404 
    116         t = template_loader.get_template('polls/results') 
    117         c = Context(request, { 
    118             'poll': p, 
    119         }) 
    120         return HttpResponse(t.render(c)) 
     105        p = get_object_or_404(polls, pk=poll_id) 
     106        return render_to_response('polls/results', {'poll': p}) 
    121107 
    122108This is almost exactly the same as the ``detail()`` view from `Tutorial 3`_.