3编写第一个django应用(投票应用),第三部分简要过程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3编写第一个django应用(投票应用),第三部分简要过程相关的知识,希望对你有一定的参考价值。
第三部分官网参考链接 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>
以上是关于3编写第一个django应用(投票应用),第三部分简要过程的主要内容,如果未能解决你的问题,请参考以下文章