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

一:开始写polls的views(视图)

polls/views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,Http404
from django.template import RequestContext,loader

from .models import Question

# 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)

def vote(request,question_id):
    return HttpResponse("You're voting on question %s." % question_id)

二:改变polls的urls

polls/urls.py

from django.conf.urls import url

from . import views

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

三:写polls的templates(模板)

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ tree polls/templates/
polls/templates/
└── polls
    ├── detail.html
    └── index.html

1 directory, 2 files

polls/templates/polls/index.html

polls/templates/polls/detail.html


参考资料:

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