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. Spark Launcher

  2. ruby **option作为函数参数,map的key必须是符号

    # NEW UNNAMED KEYWORD ARGUMENTSdef new_way(**options)return options[:foo]end# => :new_waynew_way( ...

  3. Eclipse空白包的显示和隐藏

    Eclipse空白包的显示和隐藏 点击三角形, ,下拉 -> Customize View... -> Empty packages (勾选)

  4. switch case :在JDK 7中,又加入了对String类型的支持,从此不用再写If-Else来判断字符串了

    switch的case语句可以处理int,short,byte,char类型的值, 因为short,byte,char都会转换成int进行处理,这一点也可以从生成的字节码看出. char a = 'e ...

  5. shell脚本分析apache日志状态码

    一.首先将apache日志按天切割 vi /etc/httpd/conf/httpd.conf        ErrorLog "|rotatelogs /var/log/httpd/%Y% ...

  6. [转]The NTLM Authentication Protocol and Security Support Provider

    本文转自:http://davenport.sourceforge.net/ntlm.html#ntlmHttpAuthentication The NTLM Authentication Proto ...

  7. xcode开启后,每次调试运行要输入密码

    1.contorl+空格 打开终端 2.输入DevToolsSecurity --status查看状态,如果是Developer mode is currently disabled.那就对了 3.输 ...

  8. StatusStrip控件

    态栏用于显示用户状态的简短信息.   StatusStrip控件是由system.windows.forms.statusStrip类提供,作用是在应用程序中标识对话框底部的一栏,通常用于显示应用程序 ...

  9. 京东-Java开发工程师-一面

    时间:2017-4-7 16:47 时长:32分19秒 类型:笔试前电话面试 之前打过一个电话过来说了一声,下午就直接打过来面试了,没有自我介绍貌似 1. 你做的这些东西是什么样的? 2. 选一个你觉 ...

  10. 五、standalone运行模式

    在上文中我们知道spark的集群主要有三种运行模式standalone.yarn.mesos,其中常被使用的是standalone和yarn,本文了解一下什么是standalone运行模式,它的运行流 ...