新手做的笔记,很可能会有理解错误的地方.欢迎拍砖.
在polls/views.py中增加下面内容,完善功能.
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
修改polls/urls.py的内容如下:
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
^(?P<question_id>[0-9]+)/$是正则匹配.
修改polls/view.py的index函数.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
查出前5个问题,放到context中.
因为一个django的project可能有多个app,所以要加上"命名空间".在polls/urls.py中加入
app_name = 'polls'
新建文件夹polls/templates/polls/,在新建的文件夹里加入index.html,内容如下:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
url对应mysite/url.py中的url,polls是命名空间,