接着上一节(二)的内容,首先启动站点,通过界面添加Question和Choice两张表的数据,因为接下来,要向polls app里面添加views.

1.添加数据如下(这里是通过界面操作添加的数据)

Question

Choice

     2.添加views

编写polls/views.py,添加detail(指定question的详情),results(指定question的投票结果),vote(指定question投票),每个view指定question_id作为参数,添加如下代码:

 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)

实际上这里所说的view,就是指polls/views.py中定义的一个一个的函数(action),python中函数名要全小写,如果必须有大写,不会报错,但是在路由体系中,是大小写敏感的,如果url中有大写自动转换成小写,但是如果,在定义urls.py中出现大写的定义,该view就无法访问,这个在下面会验证,这里全部采用小写.接下来把新定义的view添加到polls/urls.py路由中:

 from django.urls import path
from . import views
urlpatterns=[
path('first/',views.index,name='index'),
path('<int:question_id>/detail',views.detail,name="detail"), #定义detail view
path('<int:question_id>/results',views.results,name='results'),#定义格式:/参数[参数类型为int]/results
path('vote/<int:question_id>',views.vote,name='vote') #定义格式:vote/参数[参数类型为int]
]

根据刚刚定义的路由格式,分别查看

http://localhost:8008/polls/1/detail

http://localhost:8008/polls/vote/1

http://lcoalhost:8008/polls/vote/abce

接下来验证路由大小写的问题,修改polls/urls.py如下:

    #这里将原来的vote/<int:question_id>改成<Vote/<int:question_id>
path('Vote/<int:question_id>',views.vote,name='Vote') #定义格式:vote/参数[参数类型为int]

http://localhost:8008/polls/vote/1   #url即使输入的有大写,也会自动转换成小写,所以在定义ulrs.py的时候 全部采用小写

         3.添加views模板

上面用了大篇幅完成了向app polls中添加view(action),但是我们并不是每一次都希望view就返回一句话,更多时候我们需要他返回的是一个动态的,完整的页面

接下来的事情,view的主要任务是负责准备页面需要展示的数据,而由模板负责数据绑定和页面渲染,模板和view一般是一对一的

新建路径及文件 polls/templates/polls/index,现在polls目录如下:

改造polls/views.py view index 如下:

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

通过上一节的配置,和本节开始部分的努力,models 中的Question的对象已经和数据库绑定,并且带有数据:

 latest_question_list = Question.objects.order_by('-pub_date')[:5]  #按照pub_date排序,取前五条
template = loader.get_template('polls/index.html') #加载模板
HttpResponse(template.render(context, request)) #使用loader填充数据

编写polls/templates/polls/index.html如下:

{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/detail">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}

在html中直接取出view中loader填充的数据:'latest_question_list': latest_question_list在界面循环展示出来

在绑定数据到界面的时候,也可以使用render(),似乎更简洁,便捷polls/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)

      4.处理404的错误

上面通过模板生成的每一连接,连接到 http://localhost:8000/polls/(question_id)/detail,如果传入的question_id在数据库中不存在,我们就要在代码中提前处理,编辑polls/views.py/detail 如下:

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

官网后面还介绍了 Template System ,防止硬编码Url,Url命名空间等,请参考[https://docs.djangoproject.com/en/2.0/intro/tutorial03/]

Django App(三) View+Template的更多相关文章

  1. frist Django app — 三、 View

    前面已经说过了Django中model的一些用法,包括orm,以及操作的api,接下来就是搭一些简单的界面学习view——Django中的view.主要介绍以下两个方面: url映射 请求处理 模板文 ...

  2. django notes 三:Template 的查找

    django 中有 2种 Template Loader django.template.loaders.filesystem.Loader django.template.loaders.app_d ...

  3. django基础PROJECT APP View template

    project 和 app 的区别就是一个是配置另一个是代码: 一个project包含很多个Django app以及对它们的配置. 一个project的作用是提供配置文件,比方说哪里定义数据库连接信息 ...

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

    编写你的第一个 Django app,第三部分(Page 8)转载请注明链接地址 本页教程接前面的第二部分.我们继续开发 web-poll app,我们会专注于创建公共接口上 -- "视图& ...

  5. Django 基础二(View和urls)

    上一篇博文已经成功安装了python环境和Django,并且新建了一个空的项目.接下来就可以正式开始进行Django下 的Web开发了.首先进入项目的主目录: cd ./DjangoLearn/hol ...

  6. Python-Django 第一个Django app

    第一个Django app   by:授客 QQ:1033553122 测试环境: Python版本:python-3.4.0.amd64 下载地址:https://www.python.org/do ...

  7. python django基础三 模版渲染

    request对象 当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象.Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 reque ...

  8. Django基础三之视图函数

    一 Django的视图函数view 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错 ...

  9. python3开发进阶-Django视图(View)的常见用法

    阅读目录 简述Django的View(视图) CBV和FBV Request对象和Response对象 Django组件(render,redirect)详解 一.简述Django的View(视图) ...

随机推荐

  1. C#设计模式之二十二备忘录模式(Memeto Pattern)【行为型】

    一.引言   今天我们开始讲"行为型"设计模式的第十个模式,该模式是[备忘录模式],英文名称是:Memento Pattern.按老规矩,先从名称上来看看这个模式,个人的最初理解就 ...

  2. 统计nginx单个IP访问日志并获取IP来源

    #!/usr/bin/env python #coding=utf-8 import requests from urllib2 import urlopen # import lxml.html f ...

  3. hashCode花式卖萌

    声明:这篇博文纯属是最近看源码时闲着没事瞎折腾(好奇心驱动),对实际的应用程序编码我觉得可能没有那么大的帮助,各位亲就当是代码写累了放松放松心情,视为偏门小故事看一看就可以了,别深究. 一.从Obje ...

  4. 搭建redis cluster

    1  下载 redis安装包 tar zxvf redis-3.0.2.tar.gz cd redis-3.0.2/ make make install 2安装ruby sudo apt-get in ...

  5. C#语言和SQL Server第十三 十四章笔记

    十三章  使用ADO.NET访问数据库 十四章使用ADO.NET查询和操作数据库 十三章:                                                       ...

  6. Vue-cli 创建的项目如何跨域请求

    感谢BeArchitect的技术支持 问题描述: 使用 Vue-cli 创建的项目,开发地址是 localhost:8023,需要访问 localhost:9000 上的接口 分析原因: 不同域名之间 ...

  7. Micropython教程之TPYBoard制作蓝牙+红外循迹小车

    1.实验目的 学习在PC机系统中扩展简单I/O接口的方法. 进一步学习编制数据输出程序的设计方法. 学习蓝牙模块的接线方法及其工作原理. 学习L298N电机驱动板模块的接线方法. 学习蓝牙控制小车的工 ...

  8. 动手搭建第一个小程序音视频Demo

    欢迎大家前往云+社区,获取更多腾讯海量技术实践干货哦~ 作者:小程序音视频产品经理 腾讯云提供了全套技术文档和源码来帮助您快速构建一个音视频小程序,但是再好的源码和文档也有学习成本,为了尽快的能调试起 ...

  9. flex盒模型 详细解析

    flex盒模型 详细解析 移动端页面布局,采用盒模型布局,效果很好 /* ============================================================    ...

  10. Java学习笔记16---抽象类与接口的浅显理解

    抽象类是由abstract修饰的类,定义方式如public abstract class A{...}. 接口由interface修饰,定义方式如public interface B{...}. 抽象 ...