Python学习---django重点之视图函数

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

页面显示:

image

 

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

页面显示:

image

自定义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})

页面显示:

image

遇到的问题:

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

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

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

猜你喜欢

转载自www.cnblogs.com/ftl1012/p/9398254.html