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. dip,px,sp区别及使用场景

    1.区别 dip(device independent pixels)——设备独立像素:这个和设备硬件有关,一般哦我们为了支持WCGA.HVGA和QVGA推荐使用这个,不依赖于像素.等同于dp. px ...

  2. UI的线程问题:单线程原因及更新UI的四种方式

    1.UI线程为什么设计为单线程? UI控件的操作不是线程安全的,对于多线程并发访问的时候,如果使用加锁机制会导致: UI控件的操作变得很复杂. 加锁的操作必定会导致效率下降. 所以android系统在 ...

  3. Office 的下载、安装和激活(图文详细)

    不多说,直接上干货! 在这里,推荐一个很好的网址,http://www.itellyou.cn/ 销售渠道不同,激活通道也不同.有零售版,有大客户版.零售的用零售密钥激活,一对一. SW开头或在中间有 ...

  4. java.lang.IllegalArgumentException: Comparison method violates its general contract!

    这个错误就是写比较器的时候少写了返回值的情况: 比如: Collections.sort(list, new Ordering<QtmSysUserListDto>() { @Overri ...

  5. java多线程---------java.util.concurrent并发包----------ThreadPoolExecutor

    ThreadPoolExecutor线程池 一.三个构造方法 ThreadPoolExecutor(int corePoolSize,int MaxmumPoolSize,long KeepAlive ...

  6. try catch finall 结构里的 return

    public class ExceptionDemo1 { public static void main(String[] args) { try { ; /b; System.out.printl ...

  7. 玩转树莓派《三》——Scratch

    今天大姨妈折磨了一整个白天,稍微好点,现在打开实验楼,看到有个朋友回答了关于ubuntu上面操作SQL 的时候到处数据到txt文件,被批评没有思考问题,或许吧,虽然那个权限我现在想起确实是可读可写的, ...

  8. oracle 多列数据相同,部分列数据不同合并不相同列数据

    出现这样一种情况: 前面列数据一致,最后remark数据不同,将remark合并成 解决办法: 最后一列:结果详情: 使用到的语句为: select a,b,c,wm_concat(d) d,wm_c ...

  9. 理解B+树算法和Innodb索引

    一.innodb存储引擎索引概述: innodb存储引擎支持两种常见的索引:B+树索引和哈希索引. innodb支持哈希索引是自适应的,innodb会根据表的使用情况自动生成哈希索引. B+树索引就是 ...

  10. JDBC入门(3)--- PrepareStatement

    一.PrepareStatement概述 PrepareStatement是Statement接口的子接口: 1.强大之处: 防SQL攻击: 提高代码的可读性: 提高效率; 2.PrepareStat ...