在Django中,网页和其他内容是通过视图传递的。每个视图由一个简单的Python函数表示,Django将通过检查请求的URL(准确地说,是域名后面的部分URL)来选择一个视图。

例如,用户在浏览器中访问 <<domain>>/newsarchive/<year>/<month>/  diango的URLConfs 将请求URL与对应的views function 匹配,调用view function 进行数据处理,然后选择对应的template模板进行渲染展示或直接数据返回。

在我们的poll app中,我们将会创建以下四个视图views:

  • Question “index” page – displays the latest few questions.
  • Question “detail” page – displays a question text, with no results but with a form to vote.
  • Question “results” page – displays results for a particular question.
  • Vote action – handles voting for a particular choice in a particular question.

编写views

polls/views.py:

from django.http import HttpResponse

# Create your views here.
def index(request):
return HttpResponse("Hello, world. You're at the polls index.") 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与Views

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'),
# 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'),
]

URLconfs 中,正则表达式中的分组()作为参数传递给view,如url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail')

假如请求url为 polls/34/  相当于调用detail(request,question_id='34')

分别访问一下url可见调用不同的view 函数进行相应

http://localhost:8000/polls/

http://localhost:8000/polls/34/

http://localhost:8000/polls/34/results/

http://localhost:8000/polls/34/vote/

编写Views的数据库处理逻辑

view的主要工作:获取请求内容,调用数据库model获取数据库数据,调用业务处理Model逻辑处理,将处理结果渲染到指定的模板template中,响应response到客户端浏览器

创建 polls/templates,django会在在app目录下查找templates目录作为模板路径

创建 polls/templates/polls/index.html

Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html.

(当然templates下不创建polls,模板路径调用index.html 也可以,但是强烈不建议这样,因为避免出现不同的app中有相同名称的模板文件时读取区分不出来)

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

更新 index view in polls/views.py:

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)

访问 http://localhost:8000/polls/

编写Views 404异常

更新detail view in polls/views.py:

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(),get_list_or_404() 当获取不到对象时,返回404页面

访问 http://localhost:8000/polls/34/

使用template模板

添加 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>

django模板系统使用双大括号访问变量属性,如{{question.question_text}},

django模板中,使用 {%  %}   将原生pyton语句包含起来,其中以上实例中,使用了for循环:{% for %} {% endfor %}

访问 http://localhost:8000/polls/1

修改template模板中的hardcoded URLs,统一使用{% url %} 标签替换

如polls/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>

这种URL 查找方式是通过polls.urls 中的name来匹配,如:

mysite/urls.py:

url(r'^polls/', include('polls.urls', namespace="polls")),

polls/urls.py:

# the 'name' value as called by the {% url %} template tag

url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

添加 URL namespace

如上例,使用{% url 'detail' %} 可以根据polls.urls 中的name='detail' 来匹配。如果在同一个project下有多个app,其中都有name='detail' 时,又该如何匹配views呢?

解决方法是,添加namespace到URLconf中,如在polls/urls.py 中添加: app_name = 'polls'

则可以在模板中修改{% url 'detail' %} 为 {% url 'polls:detail' %}

访问:http://localhost:8000/polls/

点击“what's up” 链接


***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***

Django基础,Day4 - views 详解的更多相关文章

  1. 基础拾遗------redis详解

    基础拾遗 基础拾遗------特性详解 基础拾遗------webservice详解 基础拾遗------redis详解 基础拾遗------反射详解 基础拾遗------委托详解 基础拾遗----- ...

  2. 基础拾遗------webservice详解

    基础拾遗 基础拾遗------特性详解 基础拾遗------webservice详解 基础拾遗------redis详解 基础拾遗------反射详解 基础拾遗------委托详解 基础拾遗----- ...

  3. Hadoop基础-Idea打包详解之手动添加依赖(SequenceFile的压缩编解码器案例)

    Hadoop基础-Idea打包详解之手动添加依赖(SequenceFile的压缩编解码器案例) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.编辑配置文件(pml.xml)(我 ...

  4. (转)总结之:CentOS 6.5 MySQL数据库的基础以及深入详解

    总结之:CentOS 6.5 MySQL数据库的基础以及深入详解 原文:http://tanxw.blog.51cto.com/4309543/1395539 前言 早期MySQL AB公司在2009 ...

  5. Django框架 之 querySet详解

    Django框架 之 querySet详解 浏览目录 可切片 可迭代 惰性查询 缓存机制 exists()与iterator()方法 QuerySet 可切片 使用Python 的切片语法来限制查询集 ...

  6. python基础之函数详解

    Python基础之函数详解 目录 Python基础之函数详解 一.函数的定义 二.函数的调用 三.函数返回值 四.函数的参数 4.1 位置参数 4.2 关键字参数 实参:位置实参和关键字参数的混合使用 ...

  7. Django url配置 正则表达式详解 分组命名匹配 命名URL 别名 和URL反向解析 命名空间模式

    Django基础二之URL路由系统 本节目录 一 URL配置 二 正则表达式详解 三 分组命名匹配 四 命名URL(别名)和URL反向解析 五 命名空间模式 一 URL配置 Django 1.11版本 ...

  8. Django学习笔记之Django Form表单详解

    知识预览 构建一个表单 在Django 中构建一个表单 Django Form 类详解 使用表单模板 回到顶部 构建一个表单 假设你想在你的网站上创建一个简单的表单,以获得用户的名字.你需要类似这样的 ...

  9. django用户投票系统详解

    投票系统之详解 1.创建项目(mysite)与应用(polls) django-admin.py startproject mysite python manage.py startapp polls ...

随机推荐

  1. C#委托的介绍(delegate、Action、Func、predicate)

    委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递.事件是一种特殊的委托. 1.委托的声明 (1). delegate delegate我们常用到的一种声明   Deleg ...

  2. CentOS6.x生产环境下一键安装mono+jexus的脚本,自启动,带服务,版本号自控

    转自: http://linuxdot.net/bbsfile-3784 1.支持哪些个平台?答:暂时仅支持CentOS6.x平台,7.x未测试,欢迎测试并到群里反馈给我(昵称:无聊人士) 2.一键安 ...

  3. mysql半同步复制问题排查

    1.问题背景      默认情况下,线上的mysql复制都是异步复制,因此在极端情况下,主备切换时,会有一定的概率备库比主库数据少,因此切换后,我们会通过工具进行回滚回补,确保数据不丢失.半同步复制则 ...

  4. linux 下安装web开发环境

    以下使用 linux centos系统 一.JDK的安装 1.下载jdk-8u111-linux-x64.tar.gz 2.解压该文件,将解压后的文件复制到 /usr/local/jdk1.7 目录下 ...

  5. easy_UI

    引入js/css样式 <link rel="stylesheet" type="text/css" href="<%=path%>/ ...

  6. 移动端web开发,click touch tap区别

    转自: http://blog.csdn.net/sly94/article/details/51701188 移动端用tap时会有穿透问题 一:click与tap比较 click与tap都会触发点击 ...

  7. 解读ASP.NET 5 & MVC6系列(17):MVC中的其他新特性

    (GlobalImport全局导入功能) 默认新建立的MVC程序中,在Views目录下,新增加了一个_GlobalImport.cshtml文件和_ViewStart.cshtml平级,该文件的功能类 ...

  8. NoSql系列目录

    mongodb系列学习 Mongodb学习笔记一(Mongodb环境配置) Mongodb学习笔记二(Mongodb基本命令) Mongodb学习笔记三(Mongodb索引操作及性能测试) Mongo ...

  9. Linux CGroup之freezer分析与应用

    Linux Kernel:4.4.17 CGroup的freezer子系统对于成批作业管理系统很有用,可以成批启动/停止任务,以达到及其资源的调度. freezer子系统也有助于针对运行一组任务设置检 ...

  10. Codeforces Round #385(div 2)

    A =w= B QwQ C 题意:n个点m条边的无向图,其中有k个特殊点,你在这张图上尽可能多的连边,要求k个特殊点两两不连通,问最多能连多少边 分析:并查集 对原图做一次并查集,找出特殊点所在集合中 ...