Writing your first Django app, part 4--学习笔记

这一节主要写了一个对question投票的from表单;学着使用django的通用视图。

一:urls 部分修改

polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
        url(r'^$',views.IndexView.as_view(),name='index'),
        url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(),name='detail'),
        url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
        url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),
]

二:views 部分修改

polls/views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.template import RequestContext,loader
from django.core.urlresolvers import reverse
from django.views import generic

from .models import Question,Choice

# Create your views here.

def index(request):
    #return HttpResponse("Hello, world.You're at the polls index.")
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    #output = ','.join([p.question_text for p in latest_question_list])
    #return HttpResponse(output)
    #template = loader.get_template('polls/index.html')
    #context = RequestContext(request,{
    #    'latest_question_list': latest_question_list,
    #    })
    #return HttpResponse(template.render(context))
    context = {'latest_question_list': latest_question_list}
    return render(request,'polls/index.html',context)

def detail(request,question_id):
    #return HttpResponse("You're looking at question %s." % question_id)
    #try:
    #    question = Question.objects.get(pk=question_id)
    #except Question.DoesNotExist:
    #    raise Http404("Question does not exist")
    question = get_object_or_404(Question,pk=question_id)
    return render(request,'polls/detail.html',{'question': question})

def results(request,question_id):
    #reponse = "You're looking at the results of question %s."
    #return HttpResponse(reponse % question_id)
    question = get_object_or_404(Question,pk=question_id)
    return render(request,'polls/results.html',{'question': question})

def vote(request,question_id):
    #return HttpResponse("You're voting on question %s." % question_id)
    p = get_object_or_404(Question,pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError,Choice.DoesNotExist):
        return render(request,'polls/detail.html',{
                'question': p,
                'error_message': "You didn't select a choice"
                })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    def get_queryset(self):
        return Question.objects.order_by("-pub_date")[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

三:templates 模板部分修改

polls/templates/polls/detail.html

polls/templates/polls/results.html


参考资料:

Writing your first Django app, part 4:https://docs.djangoproject.com/en/1.8/intro/tutorial04/