django重点之视图函数

http请求中产生两个核心对象:

http请求:HttpRequest对象,由Django自己创建

http响应:HttpResponse对象,由开发自己创建,必须返回一个response对象

所在位置:django.http

之前我们用到的参数request就是HttpRequest    检测方法:isinstance(request,HttpRequest)

HttpRequest对象的属性和方法:

print(request.GET)     # 包含所有HTTP GET参数的类字典对象
print(request.path) # 获取请求页面的全路径,不包括域名
print(request.COOKIES) # 包含所有cookies的标准Python字典对象;keys和values都是字符串。
print(request.FILES) # 包含所有上传文件的类字典对象;
# FILES中的每一个Key都是<input type="file" name="" />标签中name属性的值,
# FILES中的每一个value同时也是一个标准的python字典对象,
# 包含下面三个Keys:filename,content_type, content
print(request.user) # 代表当前登陆的用户
# 可以通过user的is_authenticated()方法来辨别用户是否登陆:
print(request.session) # session: 唯一可读写的属性,代表当前会话的字典对象;
if request.method == "POST": # 注意是大写
注意一个常用方法:request.POST.getlist('')

HttpResponse对象:

locals()

redirect()

在HttpResponse对象上扩展的常用方法:


1 页面渲染:         render()(推荐)

render_to_response(), 需要导入render_to_response模块
2 页面跳转:         redirect("路径")
3 locals():         可以直接将函数中所有的变量传给模板

Locals()实例讲解

settigs.py:

'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 设置templates的路径为Django以前版本
# 'DIRS': [], # 注释掉该行,此为Django 2.0.1最新版本
# 'django.middleware.csrf.CsrfViewMiddleware',
...省略默认配置
STATIC_URL = '/static/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) # 原配置
# 静态资源文件
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号

templates/locals.html

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"></head>
<body>
{#传统写法#}
{# <h2> hello {{ world }}</h2> {#注意,2个大括号内只能放置一个变量#}
{# <h2> hello {{ year }} </h2> {#注意,2个大括号内只能放置一个变量#}
{#高级写法#}
<h2>world</h2>
<h2>year</h2>
</body>
</html>

mysite2/urls.py

from django.contrib import admin
from django.urls import path
from blog import views
from django.conf.urls import url
urlpatterns = [
# locals写法
url(r'locals/', views.locals_def), # 将路径名跟函数进行映射
]

views.py

from django.shortcuts import render, HttpResponse,render_to_response
import datetime
# locals操作
def locals_def(request):
year="2020"
world="world"
# return render(request, 'locals.html', {"world":world,"yeae":year}) # 传统写法
# locals仅仅需要返回函数名即可,表示使用本地变量
return render_to_response('locals.html', locals()) # 少了一个参数
# 注意:render()和render_to_response()的区别是需要添加参数request

页面显示:

Redirect()实例讲解

settigs.py

'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 设置templates的路径为Django以前版本
# 'DIRS': [], # 注释掉该行,此为Django 2.0.1最新版本
# 'django.middleware.csrf.CsrfViewMiddleware',
...省略默认配置
STATIC_URL = '/static/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) # 原配置
# 静态资源文件
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号

templates/X.html

mysite2/urls.py

from django.contrib import admin
from django.urls import path
from blog import views
from django.conf.urls import url
urlpatterns = [
# redirect写法
url(r'redirect/', views.redirect_def)
]

views.py

from django.shortcuts import render, HttpResponse,redirect
import datetime
# redirect 操作
def redirect_def(request):
return redirect("https://www.baidu.com")

页面显示:

自定义Redirect()跳转

settigs.py

'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 设置templates的路径为Django以前版本
# 'DIRS': [], # 注释掉该行,此为Django 2.0.1最新版本
# 'django.middleware.csrf.CsrfViewMiddleware',
...省略默认配置
STATIC_URL = '/static/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) # 原配置
# 静态资源文件
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号

templates/ logging.html

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"></head>
<body>
<form action="/logging" method="post"> {# 注意,action外部没有引号,大括号里面url 引号XXX #}
<input type="text" name="user"> {# 注意,这里只能用name,不能用id哈 #}
<input type="password" name="pass"> {# 注意,这里只能用name,不能用id哈 #}
<input type="submit" value="submit">
</form>
</body>
</html>

templates/ home.html

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> </head>
<body>
<h2 align="center">欢迎{{ name_logging }}登陆</h2>
</body>
</html>

mysite2/urls.py

from django.contrib import admin
from django.urls import path
from blog import views
from django.conf.urls import url
urlpatterns = [
# logging
# url(r'logging/', views.logging), # 错误的,如果后面还有匹配的内容,这里不用添加斜杠[系统匹配自动添加]
url(r'logging', views.logging), # 如果后面还有匹配的内容,这里不用添加斜杠
# home
url(r'home/', views.home),
]

views.py

from django.shortcuts import render, HttpResponse
import datetime
def logging(request):
if request.method == "POST":
if 1: # 提交的数据跟数据库进行匹配
return redirect("/home/") # 登陆成功后去home界面,但是无法看到登陆的用户
# name_logging = 'FTL # 不添加此变量和locals(),return的时候不传递任何值给home
# return render(request, 'home.html', locals())
return render(request, 'logging.html') def home(request):
name_logging = 'FTL'# logging()传递变量后,此处可以不用写变量,但是home代码报错,页面显示OK
return render(request, 'home.html', {"name_logging": name_logging})

页面显示:

遇到的问题:

1.进行url匹配的时候,一定要注意,因为logging前面系统自动补位一个斜杠[/logging]进行匹配,当调跳转到home的时候,系统也会自动部位一个url[/home],所以进行跳转的时候,logging的匹配是[r'logging']

2. 使用redirect() 时,URL会进行跳转,变量使用函数内部的变量

使用render()时,URL需要传递变量给home函数,否则页面无法显示变量内容

Python学习---django重点之视图函数的更多相关文章

  1. Python学习---Django重点之静态资源配置

    [官网静态文件介绍] https://docs.djangoproject.com/en/1.10/howto/static-files/ # settings.py 配置静态资源文件 # STATI ...

  2. Python学习---django模板语法180122

    django模板语法[Template] 模版的组成:  HTML代码+逻辑控制代码  <h1> {{ user_name }} </h1> 逻辑控制代码的组成: 1.变量: ...

  3. Django Views(视图函数)

    http请求中产生两个核心对象: http请求:HttpRequest对象 http响应:HttpResponse对象 所在位置:django.http 之前我们用到的参数request就是HttpR ...

  4. Django之views视图函数

    views视图函数属于MTV中逻辑处理的部分视图函数包含着两个对象,HttpRequest对象和HttpResponse对象 一.HttpRequest对象 HttpRequest对象在Django中 ...

  5. Python学习---Django拾遗180328

    Django之生命周期 前台发送URL请求到Django的中间件进行内容校验,完成校验后到达路由映射文件url.py,然后调用视图函数views.py里面的函数进行内容处理[ 1.操作数据库进行数据读 ...

  6. Python学习---Django路由系统【all】

    Django URL (路由系统) Django URL (路由系统): URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL模式以及要为该URL模式调用的视图函数之间的映 ...

  7. Python学习【第九篇】函数

    函数 函数是什么? 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上而下实现功能,其往往用一段代码来实现指定功能,开发过 ...

  8. Django创建通用视图函数

    想在我们有两个视图: def thinkingview(request): user = request.user if request.method == 'GET': return render( ...

  9. Python学习笔记014——迭代工具函数 内置函数enumerate()

    1 描述 enumerate() 函数用于将一个可遍历的数据对象(如列表.元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中. 2 语法 enumerate(sequ ...

随机推荐

  1. android开发之提高应用启动速度_splash页面瞬间响应_避免APP启动闪白屏

    Application和Activity中的onCreate都进行了优化,基本没有耗时操作,但是启动应用之后还是会闪现一下白色背景,然后才进入Splash页面,对比了一下QQ.微信.微博等客户端,点击 ...

  2. PHP之string之addcslashes()函数使用

    addcslashes (PHP 4, PHP 5, PHP 7) addcslashes - Quote string with slashes in a C style addcslashes - ...

  3. WPF中使用相对资源来进行绑定,数据源是通过DataContext来指定的

    1. 最外层是Window是对象,Window的ItemsControl使用了ItemsTemplate,然后在ItemsTemplate中要绑定Language属性, 而整个Window的数据源是通 ...

  4. java1.8中ConcurrentHashMap

    java1.8中的ConcurrentHashMap做了非常大的改动,整个数据结构都发生了变化,已经不存在segment了.所以要好好重新查看下源码.这篇博客是逐步更行的,看一点写一点. 首先看一个很 ...

  5. kd树 C++实现

    参考:百科kd-tree /* * kdtree.h * * Created on: Mar 3, 2017 * Author: wxquare */ #ifndef KDTREE_H_ #defin ...

  6. Linux系统快速查找文件

    有时候下载新的文件或安装新的包 但是却搞不清默认放在哪个目录了,这个时候可以使用locate命令进行快速模糊查找 比如我使用 go get github.com/coreos/bbolt/... 在一 ...

  7. *2-3-7-加入field_automation机制

    在2.3.3节中引入my_mointor时,在my_transaction中加入了my_print函数: 在2.3.5节中引入reference model时,加入了my_copy函数: 在2.3.6 ...

  8. 证书透明度Certificate Transparency

    发现使用google浏览器访问HTTPS网址时,点击小锁-->>连接-->>有一项服务器未提供任何 certificate transparency 信息?只有google浏览 ...

  9. Spring @Transactional踩坑记

    @Transactional踩坑记 总述 ​ Spring在1.2引入@Transactional注解, 该注解的引入使得我们可以简单地通过在方法或者类上添加@Transactional注解,实现事务 ...

  10. 转:详解PV、UV、VV、IP及其关系与计算

    一.什么是PV? PV即Page View,网站浏览量,指页面浏览的次数,用以衡量网站用户访问的网页数量.用户每次打开一个页面便记录1次PV,多次打开同一页面则浏览量累计.一般来说,PV与来访者的数量 ...