本教程从教程 2 停止的地方开始。我们是 继续网络投票应用程序,并将专注于创建公众界面 – “视图”。

在我们的投票应用程序中,我们将有以下四个视图:

  • 问题“索引”页面 – 显示最新的几个问题。
  • 问题“详细信息”页面 – 显示问题文本,没有结果,但 用表格投票。
  • 问题“结果”页面 – 显示特定问题的结果。
  • 投票操作 – 处理对特定选项的投票 问题。

一、写入更多视图

现在,让我们再向 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)

通过添加这些新视图到 polls.urls  以下  path()调用将连接到模块中:

from django.urls import path

from . import views

urlpatterns = [
# ex: /polls/
path("", views.index, name="index"),
# ex: /polls/1/
path("<int:question_id>/", views.detail, name="detail"),
# ex: /polls/1/results/
path("<int:question_id>/results/", views.results, name="results"),
# ex: /polls/1/vote/
path("<int:question_id>/vote/", views.vote, name="vote"),
]

启动服务后,就可以访问浏览器了 url地址 :  /polls/1/ ;  /polls/1/results/ ;  /polls/1/vote/

二、编写实际执行某些操作的视图

from django.http import HttpResponse

from .models import Question

def index(request):
latest_question_list = Question.objects.order_by("-pub_date")[:5]
output = ", ".join([q.question_text for q in latest_question_list])
return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged

但是,这里有一个问题:页面的设计在视图中是硬编码的。如果 你想改变页面的外观,你必须编辑这个Python代码。

因此,让我们使用 Django 的模板系统将设计与 Python 分开 创建视图可以使用的模板。

首先,在 polls 下 创建一个 templates 目录,Django 会在那里寻找模板,在 templates 目录下 再创建一个   polls 目录

然后创建一个html文件: index.html.也就是说你的模版文件在这个路径: polls/templates/polls/index.html

将以下代码放入该模板 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 %}

现在,让我们更新视图  polls/views.py 以使用该模板:

from django.http import HttpResponse
from django.template import loader from .models import Question def index(request):
latest_question_list = Question.objects.order_by("-pub_date")[:5]
template = loader.get_template("polls/index.html")
context = {
"latest_question_list": latest_question_list,
}
return HttpResponse(template.render(context, request))

该代码加载调用的模板并向其传递 上下文。上下文是将模板变量名称映射到 Python 的字典 对象。polls/index.html

通过将浏览器指向“/polls/”来加载页面,您应该会看到一个 包含教程 2 中的 “What’s up”问题的项目符号列表。该链接指向问题的详细信息页面。

三、一个快捷方式:render()

加载模板、填充上下文并返回带有渲染结果的 HttpResponse 对象是一个非常常见的习惯用语 模板。Django 提供了一个快捷方式。这是完整视图, 重写:index()

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)

四、引发 404 错误

现在,让我们处理问题详细信息视图 - 显示问题文本的页面 对于给定的民意调查。这是视图

from django.http import Http404
from django.shortcuts import render from .models import Question # ...
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, "polls/detail.html", {"question": question})

这里的新概念:视图引发 Http404 异常 如果不存在具有请求 ID 的问题。

我们将讨论您可以在该模板 polls/detail.html 中放入的内容 稍后,但如果您想快速让上面的示例工作,请提供一个文件 仅包含:

{{ question }}

六、快捷键:get_object_or_404()

如果对象不存在,使用 get() 并引发 Http404 是一个非常常见的习惯用法。姜戈 提供快捷方式。这是重写detail()的视图:

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})

get_object_or_404() 函数采用 Django 模型 作为它的第一个参数和任意数量的关键字参数,它 传递给 get() 函数 模特的经理。如果对象没有,它会引发 Http404 存在。

还有一个 get_list_or_404() 函数,它可以工作 就像 get_object_or_404() 一样 – 除了使用 filter() 而不是 get()。如果列表为空,它将引发 Http404

七、使用模板系统

返回到detail()我们的投票应用程序的视图。鉴于上下文 question 变量,这是模板可能的样子 喜欢:polls/detail.html

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

模板系统使用点查找语法来访问变量属性。在 的例子,首先 Django 做字典查找 在对象上。如果做不到这一点,它会尝试属性查找 - 这 在这种情况下,有效。如果属性查找失败,它将尝试 列表索引查找。{{ question.question_text }}question

方法调用发生在 {% for %} 循环中:被解释为 Python 代码,它返回对象的可迭代对象,并且 适合在 {% for %} 标记中使用。

八、删除模板中的硬编码网址

请记住,当我们在模板中编写指向问题的链接时,链接是部分硬编码的,如下所示:polls/index.html

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

这种硬编码、紧密耦合方法的问题在于它变成了 在具有大量模板的项目上更改 URL 具有挑战性。然而,由于 您在 的 path() 函数中定义了 name 参数 该模块,您可以消除对特定 URL 路径的依赖 使用模板标记在 URL 配置中定义:polls.urls{% url %}

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

其工作方式是查找模块中指定的 URL 定义。您可以准确看到“详细信息”的URL名称在哪里 定义如下:polls.urls

...
# the 'name' value as called by the {% url %} template tag
path("<int:question_id>/", views.detail, name="detail"),
...

九、命名空间 URL 名称

教程项目只有一个应用程序polls .在真实的 Django 项目中, 可能有五个、十个、二十个或更多应用程序。Django 如何区分 它们之间的 URL 名称?例如polls,应用具有detail视图,博客的同一项目上的应用也可能具有视图。如何 让 Django 知道在使用模板标签时要为 URL 创建哪个应用程序视图?{% url %}

答案是将命名空间添加到您的 URLconf。在文件polls/urls.py中,继续并添加一个 app_name 以设置应用程序命名空间:

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/index.html

polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

指向命名空间详细信息视图:

polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

当您熟悉编写视图时,请阅读本教程的第 4 部分,了解有关表单处理和泛型的基础知识 视图。

----------------------------------------------end----------------------------------------------

编写你的第一个 Django 应用程序,第3部分的更多相关文章

  1. 编写你的第一个django应用程序2

    从1停止的地方开始,我们将设置数据库,创建您的第一个模型,并快速介绍django自动生成的管理站点 数据库设置 现在,打开mysite/settings.py.这是一个普通的python模块,其中模块 ...

  2. 编写你的第一个django应用程序4

    本教程上接教程3,我们将继续开发网页投票应用,本部分将主要关注简单的表单处理以及如何对代码进行优化 写一个简单的表单 让我们更新一下在上一个教程中编写的投票详细页面的模板(‘polls/detail. ...

  3. 编写你的第一个django应用程序3

    这一篇从教程第2部分结尾的地方继续讲起.我们将继续编写投票应用,并且专注于如何创建公用界面--也被称为视图 概况 django视图概念是一类具有相同功能和末班的网页的集合,比如,在一个博客应用中,你可 ...

  4. Django教程:第一个Django应用程序(3)

    Django教程:第一个Django应用程序(3) 2013-10-08 磁针石 #承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.comqq 37391319 #博客: ...

  5. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第一部分(Page 6)

    编写你的第一个 Django app,第一部分(Page 6)转载请注明链接地址 Django 2.0.1 官方文档翻译: Django 2.0.1.dev20171223092829 documen ...

  6. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第五部分(Page 10)

    编写你的第一个 Django app,第五部分(Page 10)转载请注明链接地址 我们继续建设我们的 Web-poll 应用,本节我们会为它创建一些自动测试. 介绍自动测试 什么是自动测试 测试是简 ...

  7. 第一个Django应用程序_part3

    一.概述 此文延续第一个Django应用程序part2. 官方文档:https://docs.djangoproject.com/en/1.11/intro/tutorial03/ view是Djan ...

  8. 编写你的第一个Django应用

    安装 Python 作为一个 Python Web 框架,Django 需要 Python.更多细节请参见 我应该使用哪个版本的 Python 来配合 Django?. Python 包含了一个名为  ...

  9. 搭建你的第一个Django应用程序

    首先你要确保你机器上面安装了python:Python开发_python的安装 python的相关学习资料:http://www.cnblogs.com/hongten/tag/python/ 其次, ...

  10. Django教程:第一个Django应用程序(4)

    Django教程:第一个Django应用程序(4) 2013-10-09 磁针石 #承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.comqq 37391319 #博客: ...

随机推荐

  1. Qt编写地图综合应用文章导航

    文章 链接 1-闪烁点图 https://qtchina.blog.csdn.net/article/details/105310274 2-迁徙图 https://qtchina.blog.csdn ...

  2. Dotnetbar自定义DateTimeInput(时间)控件的显示格式,使其同时显示日期和时间

    DateTimeInput控件已有的几种格式可以在Format属性中选择: 但这几种格式仍无法满足我的要求怎么办? 例如想将显示格式定为类似这样的格式:2010-06-11 20:02:52,两步搞定 ...

  3. 视频直播技术干货(十二):从入门到放弃,快速学习Android端直播技术

    本文由陆业聪分享,原题"一文掌握直播技术:实时音视频采集.编码.传输与播放",本文进行了排版和内容优化. 1.引言 从游戏.教育.电商到娱乐,直播技术的应用场景无处不在.随着移动端 ...

  4. NVIDIA-SMI打印信息解析

  5. 前端学习openLayers配合vue3(修改地图样式)

    这一块的东西非常简单,基于上一步的继续操作 关键代码,当然对应的对象需要进行相关的引入,为了方便理解,把背景色和边框放在了一起 //填充颜色 style:new Style({ fill:new Fi ...

  6. 性能测试工具_nGrinder

    1. ngrinder-controller-3.4.3.war 放置到tomcat的webapps目录下:2. 启动tomcat;3. 访问地址: http://localhost:8080/ngr ...

  7. 直播预览层添加滤镜效果(CIFilter使用场景)

    直播预览层添加滤镜效果 原理,在显示之前,提前对图片进行滤镜处理,把处理后的图片展示出来就好了. CIFiter(滤镜类):给图片添加特殊效果(模糊,高亮等等). CIFiter滤镜分类(一个滤镜可能 ...

  8. MacBook配置

    如何在Mac上安装Java JDK及配置环境变量 1. 访问Java JDK 网站下载与安装(以JDK8为例) 点击下载链接:https://www.oracle.com/java/technolog ...

  9. RocketMQ实战—2.RocketMQ集群生产部署

    大纲 1.什么是消息中间件 2.消息中间件的技术选型 3.RocketMQ的架构原理和使用方式 4.消息中间件路由中心的架构原理 5.Broker的主从架构原理 6.高可用的消息中间件生产部署架构 7 ...

  10. JMeter + ant + Jenkins 接口测试持续集成

    JMeter + ant + Jenkins 接口测试持续集成 操作系统:linux 环境变量 地址 jdk11 https://www.oracle.com/java/technologies/do ...