views.py视图函
views.py视图函数来自 urls 的映射关系
常用所需模块
from django.shortcuts import render               # ****** 渲染 render 跳转到指定的 url.html,并且将数据 也可以 传给前端页面 {"data": DB}  DB 为后台取到的数据
from django.shortcuts import HttpResponse         # 响应一个字符串; HttpResponse 返回一个字符串 “OK”
from django.shortcuts import redirect             # redirect 重定向 依照 get 形式请求 一个url
在views.py中拼接路径
from CMS import settings
import os 
# 从项目路径导入 settings 配置文件,引用其中的BASE_DIR变量,使用join拼接具体路径
html_path=os.path.join(settings.BASE_DIR,"templates","index.html")
视图函数请求对象HttpRequest对象
属性:
path:       请求页面的全路径,不包括域名
method:     请求中使用的HTTP方法的字符串表示。全大写表示。例如
               if request.method=="POST":
                    # 如果为POST获取传来的数据
                    title=request.POST.get("title")
                    pubdate=request.POST.get("pubdate")
                    
               # 否则直接返回一个渲染的页面
               return render(request,"add.html")
GET:         包含所有HTTP GET参数的类字典对象
POST:       包含所有HTTP POST参数的类字典对象
COOKIES:     包含所有cookies的标准Python字典对象;keys和values都是字符串。
FILES:      包含所有上传文件的类字典对象;FILES中的每一个Key都是<input type="file" name="" />标签中
             name属性的值,FILES中的每一个value同时也是一个标准的python字典对象,包含下面三个Keys:
             filename:      上传文件名,用字符串表示
             content_type:   上传文件的Content Type
             content:       上传文件的原始内容
user:       是一个django.contrib.auth.models.User对象,代表当前登陆的用户。如果访问用户当前
             没有登陆,user将被初始化为django.contrib.auth.models.AnonymousUser的实例。你
             可以通过user的is_authenticated()方法来辨别用户是否登陆:
             if req.user.is_authenticated();只有激活Django中的AuthenticationMiddleware
             时该属性才可用
session:    唯一可读写的属性,代表当前会话的字典对象;自己有激活Django中的session支持时该属性才可用。
例:
1.如果使用POST方式请求获取,请求的路径
def add(request):
    if request.method=="POST":
        print(request.path)
注意:
2.键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用getlist:
def add(request):
    if request.method=="POST":
        hobby=request.POST.getlist("hobby")
输出:
hobby ["111","222"]
常用的操作
    # request.method     # 获取用户的请求方式:如果通过get请求就获取"GET",如果是post请求就获取"POST"
    # 如果是依照get方式请求,返回给页面使用  render 渲染
    
    # render            渲染
    # redirect          重定向
    # HttpResponse      http响应
常用的相应用户的请求:
    # return render(request,"login.html")               # ****** 渲染 render 跳转到指定的 url.html 
    # return render(request,"index.html",{"data": DB})  # ****** 渲染 并且将数据 也可以 传给前端页面 {"data": DB}  DB 为后台取到的数据,data为页面中的 模板调用值 {{ data }}
    # return redirect("http://www.baidu.com")           # redirect 重定向 依照 get 形式请求 一个url
    # return redirect("/index/")                        # 重定向 urls.py 里指定的 url
    # return HttpResponse("OK")                         # 响应一个字符串; HttpResponse 返回一个字符串 “OK”   
解决 硬编码
1.在返回用户请求时redirect重定向一个内部地址时,达到解决 硬编码 的问题:
在Urls.py中配置name="LOGIN": 
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views as app01_views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    
    # 用户请求url http://127.0.0.1/login.html; 即使在这里将 ^login.html/  改为 ^loginssss.html/ 对模板处的引用也不会有问题
    # 使用别名的方式 解耦 url 的变更请求;name = "LOGIN" 在模板中 引用使用  {% url 'LOGIN' %}  代替这个路径
    url(r'^login.html/', app01_views.login, name="LOGIN")
]
2.在views.py中通过redirect重定向一个地址时:
from django.shortcuts import render, HttpResponse,redirect
# 需要模块 reverse
from django.urls import reverse
def login(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        
        # 给用户返回重定向 redirect(reverse('别名')) 实现解耦 url 变更
        return redirect(reverse('LOGIN'))
    # render(request, "login.html")  表示返回 templates/ 实际的 页面名称
    return render(request, "login.html")
3.在templates模板语言中的action="{% url 'LOGIN' %}" 获取render渲染来的urls.py实际请求地址:
<body>
    {# 通过render渲染时 将urls.py定义的别名 name="LOGIN" 转换为实际的 请求路径地址 loginssss.html #}
    {# 格式 action="{% url '别名' %}";url为关键字 '别名' 为在视图函数中定义的name值 #}
    <form action="{% url 'LOGIN' %}" method="post">
    
        <p>姓名 <input type="text" name="user"></p>
        <p>密码 <input type="password" name="pwd"></p>
        <input type="submit">
    </form>
</body>
render渲染
模拟数据源:
DB = [
{"hostname":"c1.com","port":80},
{"hostname":"c2.com","port":81},
{"hostname":"c3.com","port":82},
{"hostname":"c4.com","port":83},
{"hostname":"c5.com","port":84},
]
age=18
格式:return render(request, template_name,{"data": DB,"age":age})
参数:
     request: 用于生成响应的请求对象。
     template_name:要使用的模板的完整名称,可选的参数
     {"data": DB}:添加到模板上下文的一个字典。默认可以为空。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。
     # 在传多个值时,可以直接使用 locals():return render(request, template_name, locals()) 将次 函数中所有 调用方式传入模板中;
     
渲染 并且将数据 也可以 传给前端页面 {"data": DB}  DB 为后台取到的数据,data为页面中的 模板调用值 {{ data }}     
redirect重定向
格式:return redirect("http://www.baidu.com")或 return redirect("/index/")
一个视图,可以带有参数:将使用urlresolvers.reverse 来反向解析名称
一个绝对的或相对的URL,将原封不动的作为重定向的位置。
默认返回一个临时的重定向;传递permanent=True 可以返回一个永久的重定向。
示例:
一个视图函数至少包含:
- index函数至少有一个 参数 (request)请求
- request 封装了用户请求的相关信息 (get post)
视图函数的案例:
1.URL为index的函数:
def index(request):
    print(request.GET)                     # 可以获取 客户端通过 url 地址栏传入的数据 http://127.0.0.1:8000/index/?v1=123&v2=456
                                           # 打印数据 <QueryDict: {'v1': ['123'], 'v2': ['456']}>
    if request.method == "GET":
        return render(request,"index.html",{"data": DB})             # 直接将页面跳转给 index.html 并将数据传过去 {"data": DB}
    
    elif request.method == "POST":                  # 当请求方式为 POST 表单提交时
        host = request.POST.get("host")             # 可以获取提交过来的数据,host 为提交 表单input的name值
        port = request.POST.get("port")
        if host and port:                           # 判断模板提交的数据是否有值
            temp = {"hostname":host,"port":port}
            DB.append(temp)
            return render(request, "index.html", {"data": DB})
    return redirect("/index/")                      # 如果提交数据为空直接通过 redirect 重定向到 index/
2.URL为login的函数:
def login(request):
    if request.method == "GET":
        return render(request,"login.html")
    elif request.method == "POST":
        # 获取用户提交的数据默认用户提交依照字典形式提交到后台 {'user': ['zhangsan'], 'pwd': ['pwd123']}
        print(request.POST)
        username = request.POST.get("user")
        passwrod = request.POST.get("pwd")
        if username == "root" and passwrod == "123":
            return redirect("/index/")               # 验证通过后,重定向将url指向 /index/  
        else:
            return redirect("/login/")

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号