接着昨天写的那篇笔记,今天继续学习DJango中的内容。这一章主要是介绍Django中的视图部分。

4.1视图理念

4.2编写第一个视图

4.3编写更多的视图

4.4给视图编写功能

4.5render()和404错误

4.6使用模版

4.7使用url命名空间

4.1视图理念

视图:视图(view)是Django应用中的一“类”网页,它通常使用一个特定的函数提供服务。

视图通过使用特殊的函数,传递网页页面和其他内容,同时,视图也对web请求进行回应。通过检查请求的url选择使用哪一个视图。

4.2编写第一个视图

first,

打开polls/views.py,开始编写视图函数

polls/views.py

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

second,

要在polls目录下创建一个URLconf,创建url.py文件

目录:

polls/
__init__.py
admin.py
models.py
tests.py
urls.py
views.py

同时键入代码,使网址和视图函数连接起来

polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
]

third,

在polls/urls.py中键入URLconf, 使得url可以连接到polls.urls模块

mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
]

结果,

将Index视图关联成功,浏览http://localhost:8000/polls/,会出现在视图中定义的网页内容。

解释:url()参数:(regex,view,*kwagrs,*name)

regex:正则表达式的短格式,匹配满足字符串的网页

view:找到一个正则表达时,就会调用view作为视图函数

kwargs:任何关键字参数都可以以字典形式传递给目标视图,暂不用

name:给URL命名,可以通过名称来引用URL

4.3编写更多的视图

first,编写更多的视图函数

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)

second,编写url()将函数和URL连接起来

polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), #?P<question_id> 定义一个名字,它将用于标识匹配的模式
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

打开浏览器,输入“/34/”它将运行detail()方法并显示你在URL中提供的ID。 再试一下“/polls/34/results/”和“/polls/34/vote/” —— 它们将显示出对应的结果界面和投票界面。

解释:

  • Django发现匹配到了正则表达式'^polls/'

  • 然后,Django将去掉匹配到的文本("polls/")并将剩下的文本 —— "34/" —— 发送给‘polls.urls’ URLconf 做进一步处理,这时将匹配r'^(?P<question_id>[0-9]+)/$'并导致像下面这样调用detail()视图:

  • detail(request=<HttpRequest object>, question_id='34')
    
    

    4.4给视图编写功能

    first,视图从数据库中读取记录

    polls/views.py
    
    from django.http import HttpResponse
    
    from .models import Question
    
    def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([p.question_text for p in latest_question_list])
    return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged

    second,创建模版

    这时,页面设计被硬编码在视图中,我们使用模版,使页面和视图分离出来

    在polls目录下创建templates目录,然后在templates目录下,创建另外一个目录polls,最后在其中创建文件index.html。为了避免与其他应用模版重复。

    模版位置:(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 %}

    更新视图

    polls/views.py
    
    from django.http import HttpResponse
    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)

    render()函数将请求对象作为它的第一个参数,模板的名字作为它的第二个参数,一个字典作为它可选的第三个参数。 它返回一个HttpResponse对象,含有用给定的context 渲染后的模板。

    third,处理视图函数,引发一个404错误

    polls/views.py

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

    解释:如果没有根据ID找到一个Question对象,就会引发404错误

    4.5使用模版和url命名空间

    浏览http://localhost:8000/polls/,会出现在视图中定义的网页内容。

    更改页面,detail.html模版应该是这样子的

    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>

    更改index.html,改变一部分硬编码

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

    更改为

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

    它的工作原理是在polls,urls模版中查找指定的URL,因为刚才给一个URL命名为

    detail,所以可以直接调用。

    还有一个问题。如果应用特别多,不同的应用可能拥有几个名为detail的视图。

    这个时候,在主URLconf下添加命名空间,可以防止这个问题

    首先修改urls.py

    mysite/urls.py
    
    from django.conf.urls import include, url
    from django.contrib import admin urlpatterns = [
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
    ]

    其次将

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

    修改为    【浏览http://localhost:8000/polls/,会出现在视图中定义的网页内容。】

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

4 Django应用 第3部分(视图部分)的更多相关文章

  1. Django基础(路由、视图、模板)

    目录导航 Django 路由控制 Django 视图层 Django 模版层 Django 路由控制 URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL与要为该URL调用 ...

  2. Django - 将URL映射到视图

    URLconf 就像是 Django 所支撑网站的目录.它的本质是 URL 模式以及要为该 URL 模式调用的视图函数之间的映射表.你就是以这种方式告诉 Django,对于这个 URL 调用这段代码, ...

  3. 第三百零五节,Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性

    Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性 Views(视图函数)逻辑处理,最终是围绕着两个对象实现的 http请求中产生两个核心对象: http请求:HttpRe ...

  4. Django:学习笔记(9)——视图

    Django:学习笔记(9)——视图 基础视图 基于函数的视图,我们需要在使用条件语句来判断请求类型,并分支处理.但是在基于类的视图中,我们可以在类中定义不同请求类型的方法来处理相对应的请求. 基于函 ...

  5. Django:学习笔记(8)——视图

    Django:学习笔记(8)——视图

  6. 三 Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性

    Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性 Views(视图函数)逻辑处理,最终是围绕着两个对象实现的 http请求中产生两个核心对象: http请求:HttpRe ...

  7. Django REST framework 中的视图

    1.Request REST framework传入视图的request对象不再是Django默认的Httprequest对象,而是DRF提供的扩展类的Request类的对象 常用属性 request ...

  8. DRF (Django REST framework) 中的视图类

    视图说明 1. 两个基类 1)APIView rest_framework.views.APIView APIView是REST framework提供的所有视图的基类,继承自Django的View父 ...

  9. Django与drf 源码视图解析

    0902自我总结 Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View """ 1)as_view()是入口,得到view函数地址 2) ...

  10. Django 学习之Rest Framework 视图相关

    drf除了在数据序列化部分简写代码以外,还在视图中提供了简写操作.所以在django原有的django.views.View类基础上,drf封装了多个子类出来提供给我们使用. Django REST ...

随机推荐

  1. CentOS 7 MariaDB-MHA

    关于MHA    MHA(Master High Availability)是一款开源的mysql高可用程序,目前在mysql高可用方面是一个相对成熟的解决方案.MHA 搭建的前提是MySQL集群中已 ...

  2. Fluxion无线攻击

    使用步骤 github地址 https://github.com/deltaxflux/fluxion 进入到fluxion目录下 ./fluxion 启动fluxion  启动之后会先检测没有安装的 ...

  3. CSS组合选择符

    组合选择符说明了两个选择器直接的关系. 目录: 后代选取器(以空格分隔) 子元素选择器(以大于号分隔) 相邻兄弟选择器(以加号分隔) 普通兄弟选择器(以破折号分隔) 后代选取器 后代选取器匹配所有值得 ...

  4. JVM探秘1--JVM内存运行时区域划分

    Java程序员一般不需要太关注内存,因为操作内存的权力都交给了Java虚拟机,但是Java程序员必须需要了解JVM是如何使用内存的,否则一旦内存出现泄漏或事溢出的话,就会一筹莫展不知道从哪去入手排查问 ...

  5. django+nginx+python3 生产环境部署

    一.安装python基础环境 1.安装各类基础模块 yum install  gcc-c++ wget openssl-devel bzip2-devel expat-devel gdbm-devel ...

  6. springboot跑定时任务

    使用@Scheduled注解实现 1.在启动类上加上@EnableScheduling 开启定时任务 2.新建一个任务类,在方法上添加@Scheduled注解 @Componentpublic cla ...

  7. UI自动化(三)css优先级

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  8. opencv学习之路(30)、分水岭算法及图像修补

    一.简介 二.分水岭算法 #include "opencv2/opencv.hpp" using namespace cv; void main() { Mat srcImg = ...

  9. sql添加一个list的查询条件

    编程中往往会有需要对某个list的值进行查询的需求,而将一个list作为查询条件,我所知道的有两种方法: 1.for循环遍历,每次循环一个sql,每次查list中一个条件的数据,最后累加 ...(最基 ...

  10. 剑指offer 04:重构二叉树

    题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...