您好,登录后才能下订单哦!
第三部分官网参考链接 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('<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'),
]
访问:
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 %}
<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 %}
页面添加六条数据 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('<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'),
]
修改为指向具有命名空间的详细视图:
polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。