第三部分官網(wǎng)參考鏈接 https://docs.djangoproject.com/zh-hans/2.2/intro/tutorial03/
1、編寫(xiě)更多視圖:
添加函數(shù)
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函數(shù)調(diào)用
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'),
]
訪問(wèn):
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、一個(gè)快捷函數(shù): render()的使用
(1) 編寫(xiě)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應(yīng)用下創(chuàng)建templates/polls子文件夾,再在polls/templates/polls下創(chuàng)建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 %}
頁(yè)面添加六條數(shù)據(jù) http://127.0.0.1:8000/admin
測(cè)試訪問(wèn):http://127.0.0.1:8000/polls/
3、一個(gè)快捷函數(shù): get_object_or_404()拋出404錯(cuò)誤
(1)編寫(xiě)視圖
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})
添加模板系統(tǒng)
polls/templates/polls/detail.html{{ question }}
4、為 URL 名稱(chēng)添加命名空間
在每個(gè)應(yīng)用的的urls下添加對(duì)應(yīng)的應(yīng)用名字的命名空間
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'),
]
修改為指向具有命名空間的詳細(xì)視圖:
polls/templates/polls/index.html
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。