扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
第三部分官网参考链接 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
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流