Part III official website reference link https://docs.djangoproject.com/zh-hans/2.2/intro/tutorial03/
1. Write more views:
Add function
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 function call
polls/urls.py
from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5 path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ]
Visit:
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. A shortcut function: use of render()
(1) write index view
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) add template
Create the templates / polsfolder under the polls application, and then create index.html under the polls/templates/polls
polls/templates/polls/index.html
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
Add six pieces of data to the page http://127.0.0.1:8000/admin
Test access: http://127.0.0.1:8000/polls/
3. A shortcut function: get object or 404() has a 404 error
(1) compilation view
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})
Add template system
polls/templates/polls/detail.html
{{ question }}
4. Add namespace for URL name
Add the namespace of the corresponding application name under the urls of each application
polls/urls.py
from django.urls import path from . import views app_name = 'polls' #Add namespace urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ]
Modify to point to a detail view with a namespace:
polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>