mirror of
https://github.com/django/django.git
synced 2025-08-03 18:38:50 +00:00
Changed overview and tutorial docs to use render_to_response and get_object_or_404, to cut down on code
git-svn-id: http://code.djangoproject.com/svn/django/trunk@678 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
3dcdce4d63
commit
b7528320b6
3 changed files with 62 additions and 40 deletions
|
@ -48,27 +48,20 @@ included this line::
|
|||
|
||||
So let's create a ``vote()`` function in ``myproject/apps/polls/views/polls.py``::
|
||||
|
||||
from django.core import template_loader
|
||||
from django.core.extensions import DjangoContext as Context
|
||||
from django.core.extensions import get_object_or_404, render_to_response
|
||||
from django.models.polls import choices, polls
|
||||
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
|
||||
from django.core.exceptions import Http404
|
||||
from django.utils.httpwrappers import HttpResponseRedirect
|
||||
|
||||
def vote(request, poll_id):
|
||||
try:
|
||||
p = polls.get_object(pk=poll_id)
|
||||
except polls.PollDoesNotExist:
|
||||
raise Http404
|
||||
p = get_object_or_404(polls, pk=poll_id)
|
||||
try:
|
||||
selected_choice = p.get_choice(pk=request.POST['choice'])
|
||||
except (KeyError, choices.ChoiceDoesNotExist):
|
||||
# Redisplay the poll voting form.
|
||||
t = template_loader.get_template('polls/detail')
|
||||
c = Context(request, {
|
||||
return render_to_response('polls/detail', {
|
||||
'poll': p,
|
||||
'error_message': "You didn't select a choice.",
|
||||
})
|
||||
return HttpResponse(t.render(c))
|
||||
else:
|
||||
selected_choice.votes += 1
|
||||
selected_choice.save()
|
||||
|
@ -109,15 +102,8 @@ After somebody votes in a poll, the ``vote()`` view redirects to the results
|
|||
page for the poll. Let's write that view::
|
||||
|
||||
def results(request, poll_id):
|
||||
try:
|
||||
p = polls.get_object(pk=poll_id)
|
||||
except polls.PollDoesNotExist:
|
||||
raise Http404
|
||||
t = template_loader.get_template('polls/results')
|
||||
c = Context(request, {
|
||||
'poll': p,
|
||||
})
|
||||
return HttpResponse(t.render(c))
|
||||
p = get_object_or_404(polls, pk=poll_id)
|
||||
return render_to_response('polls/results', {'poll': p})
|
||||
|
||||
This is almost exactly the same as the ``detail()`` view from `Tutorial 3`_.
|
||||
The only difference is the template name. We'll fix this redundancy later.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue