1. 编写更多视图

(python3.8) [root@node8 polls]# pwd
/blueicex/python-project/mysite/polls
(python3.8) [root@node8 polls]# vim views.py from django.shortcuts import render
from django.http import HttpResponse
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)def index(request):return HttpResponse("Hello, world. You're at the polls index.")

添加路由

(python3.8) [root@node8 polls]# pwd
/blueicex/python-project/mysite/polls
(python3.8) [root@node8 polls]# vim 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'),
]

2. 写一个真正有用的视图

每个视图必须要做的只有两件事:返回一个包含被请求页面内容的 HttpResponse 对象,或者抛出一个异常,比如 Http404 。
视图可以从数据库里读取记录,可以使用一个模板引擎(比如 Django 自带的,或者其他第三方的),可以生成一个 PDF 文件,可以输出一个 XML,创建一个 ZIP 文件。
Django 只要求返回HttpResponse ,或者抛异常。

(python3.8) [root@node8 polls]# vim views.py
from django.shortcuts import render
from django.http import HttpResponse
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)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)

页面的设计写死在视图函数的代码里

3. 模板

在 polls 目录里创建 templates 目录。Django 会在templates 目录里查找模板文件。

项目的 TEMPLATES 配置项描述了 Django 如何载入和渲染模板。默认的设置文件设置了 DjangoTemplates 后端,并将 APP_DIRS 设置成了 True。这一选项将会让 DjangoTemplates 在每个 INSTALLED_APPS 文件夹中寻找 “templates” 子目录。这就是为什么尽管没有像在第二部分中那样修改 DIRS 设置,Django 也能正确找到 polls 的模板位置的原因。
在创建的 templates 目录里,再创建一个目录 polls,新建一个文件 index.html 。因为app_directories模板加载器是通过上述描述的方法运行的,所以Django可以引用到 polls/index.html 模板了。

vim 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 里的 index 视图使用模板
vim 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))

载入 polls/index.html 模板文件,并且向它传递上下文(context)。上下文是一个字典,它将模板内的变量映射为 Python 对象。

4. 快捷函数 render()

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

不再需要导入 loader 和 HttpResponse

5. 抛出 404 错误

vim views.py
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})

6. 快捷函数 get_object_or_404()

尝试用 get() 函数获取一个对象,如果不存在就抛出 Http404 错误也是一个普遍的流程。Django 提供了一个快捷函数get_object_or_404()

vim views.py
from django.shortcuts import get_object_or_404, renderfrom .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() 而不是自己捕获 ObjectDoesNotExist 异常呢?为什么模型 API 不直接抛出 ObjectDoesNotExist 而是抛出 Http404 呢?
因为这样做会增加模型层和视图层的耦合性。Django 设计的最重要的思想之一就是要保证松散耦合
也有 get_list_or_404() 函数,工作原理和 get_object_or_404() 一样,除了 get() 函数被换成了 filter() 函数。如果列表为空的话会抛出 Http404 异常。

7. 使用模板系统

vim polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

在 {% for %} 循环中发生的函数调用:question.choice_set.all 被解释为 Python 代码 question.choice_set.all() ,将会返回一个可迭代的 Choice 对象,这一对象可以在 {% for %} 标签内部使用。

8. 去除模板中的硬编码 URL

在 polls/index.html 里编写投票链接时,链接是硬编码

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

硬编码和强耦合的链接,对于一个包含很多应用的项目来说,修改起来是十分困难的。在 polls.urls 的 url() 函数中通过 name 参数为 URL 定义了名字,使用 {% url %} 标签代替硬编码

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

在 polls.urls 模块的 URL 定义中寻具有指定名字的条目

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

改变投票详情视图的 URL,比如想改成 polls/specifics/12/ ,不用在模板里修改任何东西,只要在 polls/urls.py 里稍微修改

...
# added the word 'specifics'
path('specifics/<int:question_id>/', views.detail, name='detail'),
...

9. 为 URL 名称添加命名空间

在根 URLconf 中添加命名空间,加上 app_name 设置命名空间。

vim polls/urls.py
from django.urls import path
from . import viewsapp_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'),
]
vim polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

修改为指向具有命名空间的详细视图

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

————Blueicex 2020/07/20 22:41 blueice1980@126.com

5. 视图——Django相关推荐

  1. Django 视图函数

    定义视图 本质就是一个函数 视图的参数 一个HttpRequest实例 通过正则表达式组获取的位置参数 通过正则表达式组获得的关键字参数 在应用目录下默认有views.py文件,一般视图都定义在这个文 ...

  2. Django整理(二) - 视图和模板的初步使用

    Django中的视图 · Django使用视图来编写web应用的业务逻辑 · Django的视图也就是一个函数,可称为视图函数 · 视图定义在应用的view.py文件中 · 视图需要绑定一个URL地址 ...

  3. Django视图(一)

    Django视图(一) 文章目录 Django视图(一) 一.视图 1.视图简介 2.视图的功能 3.使用视图的过程 4.内置错误视图 二.URLconf 1.配置 2.语法 3.获取值 三.Http ...

  4. Django视图(python函数)

    1.视图 视图负责接受Web请求HttpRequest,进行逻辑处理,返回Web响应HttpResponse给请求者 响应可以是一张网页的HTML内容,一个重定向,一个404错误等 视图就是pytho ...

  5. django 视图-----视图函数

    定义视图 本质就是一个函数 视图的参数 一个HttpRequest实例 通过正则表达式组获取的位置参数 通过正则表达式组获得的关键字参数 在应用目录下默认有views.py文件,一般视图都定义在这个文 ...

  6. django模型查询_如何在Django中编写有效的视图,模型和查询

    django模型查询 I like Django. It's a well-considered and intuitive framework with a name I can pronounce ...

  7. django 1.8 官方文档翻译: 3-2-1 内建的视图

    内建的视图 有几个Django 的内建视图在编写视图 中讲述,文档的其它地方也会有所讲述. 开发环境中的文件服务器 static.serve(request, path, document_root, ...

  8. django 1.8 官方文档翻译: 3-1-2 编写视图

    Django 文档协作翻译小组人手紧缺,有兴趣的朋友可以加入我们,完全公益性质. 交流群:467338606 网站:http://python.usyiyi.cn/django/index.html ...

  9. 自学Python第二十二天- Django框架(三) AJAX、文件上传、POST 请求类型之间的转换、多APP开发、iframe、验证码、分页器、类视图、中间件、信号、日志、缓存、celery异步

    Django官方文档 django 使用 AJAX django 项目中也可以使用 ajax 技术 前端 前端和其他 web 框架一样,需要注意的是,django 接收 POST 请求时,需要 csr ...

  10. Django基础--Django基本命令、路由配置系统(URLconf)、编写视图、Template、数据库与ORM...

    web框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构. 使用框架可以帮你快速开发特定的系统. 简单地说,就是你用别人搭建好的舞台来做表演. 尝试搭建一个简单 ...

最新文章

  1. 某程序员总结大厂程序员性格:阿里出来的是人精!百度出来的脾气好!美图出来的一根筋!头条出来的心高气傲!京东出来的满嘴是兄弟!...
  2. VMware(VMDebugger)导致VS2010启动慢的解决办法
  3. 计算机名字更改时不显示文字,教大家电脑中文件夹不显示名字怎么办
  4. Customization larbin
  5. Java进阶:default方法说明
  6. 【spring boot】 mybatis配置双数据源/多数据源
  7. python回收机制
  8. [css] css中padding和margin是相对于父元素还是子元素呢?
  9. 作为研究生/博士生导师招收的第一个学生是一种怎样的体验?
  10. 数据链路层点到点通讯和PPP协议
  11. python main调试_在main.py中调试显示这个是什么问题
  12. 原始尺寸_三维扫描检测,铸件三维全尺寸检测,铸件三维扫描服务
  13. python+django+mysql疫苗预约系统毕业设计毕设开题报告
  14. WebRoot 与 WEB-INF 相关问题学习整理
  15. 图像处理-相关知识点
  16. 校招前端笔试面试回顾
  17. 移动通信模组 APN 汇总
  18. 回答阿里社招面试如何准备,顺便谈谈对于Java程序猿学习当中各个阶段的建议 - 左潇龙 - 博客园...
  19. 生活-象棋-蹩马腿-1
  20. 微信小程序开发获取AppID 和 AppSecret

热门文章

  1. 计算机学院三下乡,重庆理工大学计算机学院”三下乡“教师情牵故乡
  2. github1s 油猴插件
  3. 《高效能人士的七个习惯》读后感
  4. glide 压缩图拍呢_Glide-图片的压缩
  5. 利用matlab信号带宽,测量均值频率、功率、带宽
  6. SEM和SEO有什么区别,哪种更好一些
  7. 怎么往云服务器里传输文件,怎么把文件传输到云服务器
  8. 2019-03-02 致虚极守静笃 读老子《道德经》有感
  9. Word技巧和快捷键
  10. 并行网络测试软件,Manul:一款基于覆盖率引导的并行模糊测试工具