第三部分官网参考链接 https://docs.djangoproject.com/zh-hans/2.2/intro/tutorial03/
1、编写更多视图:
添加函数
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)
url函数调用
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5
path('/', views.detail, name='detail'),
# ex: /polls/5/results/
path('/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('/vote/', views.vote, name='vote'),
]
访问:
http://127.0.0.1:8000/polls/
http://127.0.0.1:8000/polls/5
http://127.0.0.1:8000/polls/5/results
http://127.0.0.1:8000/polls/5/vote
2、一个快捷函数: render()的使用
(1) 编写index视图
polls/views.py
from django.shortcuts import render
from .models import Question
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)
(2)添加模板
polls应用下创建templates/polls子文件夹,再在polls/templates/polls下创建index.html
polls/templates/polls/index.html
{% if latest_question_list %}
{% for question in latest_question_list %}
- {{ question.question_text }}
{% endfor %}
{% else %}
No polls are available.
{% endif %}
页面添加六条数据 http://127.0.0.1:8000/admin
测试访问:http://127.0.0.1:8000/polls/
3、一个快捷函数: get_object_or_404()抛出404错误
(1)编写视图
from django.shortcuts import get_object_or_404, render
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
添加模板系统
polls/templates/polls/detail.html{{ question }}
4、为 URL 名称添加命名空间
在每个应用的的urls下添加对应的应用名字的命名空间
polls/urls.py
from django.urls import path
from . import views
app_name = 'polls' #添加命名空间
urlpatterns = [
path('', views.index, name='index'),
path('/', views.detail, name='detail'),
path('/results/', views.results, name='results'),
path('/vote/', views.vote, name='vote'),
]
修改为指向具有命名空间的详细视图:
polls/templates/polls/index.html