在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. 利用sphinx为python项目生成API文档

    sphinx可以根据python的注释生成可以查找的api文档,简单记录了下步骤 1:安装 pip install -U Sphinx 2:在需要生成文档的.py文件目录下执行sphinx-apido ...

  2. MYSQL数据库的优化

    我们究竟应该如何对MySQL数据库进行优化?下面我就从MySQL对硬件的选择.MySQL的安装.my.cnf的优化.MySQL如何进行架构设计及数据切分等方面来说明这个问题. 服务器物理硬件的优化 在 ...

  3. Linux下面安装rpm包

    [root@localhost ~]# mount /dev/sdb4 /mnt/ [root@localhost ~]# cd /mnt[root@localhost mnt]# lsaddons ...

  4. 1-ser2008系统封装实验报告

    系统封装实验 1.       封装系统的原因 直接克隆系统会导致克隆后的系统和原系统的SID号一致,在许多实验中会因为SID号相同而影响实验效果(如活动目录) 2.       实验 首先看一下se ...

  5. Ubuntu Server 设置PPTP客户端连接

    安装PPTP客户端 apt-get install pptp-linux 设置连接账号信息 sudo vim /etc/ppp/chap-secrets 其中$login_name是登录名:$pass ...

  6. MyBatis源码分析-SQL语句执行的完整流程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  7. EXCEL中对1个单元格中多个数字求和

    如A1=3779.3759.3769.3781.3750,A2对A1中4个数字求和怎么求!请高手赐教! 方法一:在B1中输入公式=SUM(MID(A1,{1,6,11,16,21},4)*1) 方法二 ...

  8. heredoc技术

    Heredoc技术,在正规的PHP文档中和技术书籍中一般没有详细讲述,只是提到了这是一种Perl风格的字符串输出技术.但是现在的一些论坛程序,和部分文章系统,都巧妙的使用heredoc技术,来部分的实 ...

  9. [LeetCode] Heaters 加热器

    Winter is coming! Your first job during the contest is to design a standard heater with fixed warm r ...

  10. 用jQuery获取表单的值

    在日常开发过程中,有许多用到表单的地方.比如登录,注册,比如支付,填写订单,比如后台管理等等. 使用jQuery来获取表单的值是比较常见的做法. 常见表单 单行文字域:<input type=' ...