3、render使用添加命名空间抛出404错误
第三部分官网参考链接 https://docs.djangoproject.com/zh-hans/2.2/intro/tutorial03/
1、编写更多视图:
添加函数
polls/views.py
创新互联专注为客户提供全方位的互联网综合服务,包含不限于成都做网站、网站制作、邯郸网络推广、小程序制作、邯郸网络营销、邯郸企业策划、邯郸品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供邯郸建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com
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
网站栏目:3、render使用添加命名空间抛出404错误
浏览路径:http://azwzsj.com/article/iephdd.html