Django Review of _05_ Login Case

view:

1. Function view

接收请求,进行处理,与M和T进行交互,返回应答。
返回html内容HttpResponse,也可能重定向redirect,还可能是JsonResponse

2. View function uses

2.1

1) view function is defined

request参数必须有,是一个HttpRequest类型的对象。参数名可以变化,但不要更改。

2) Configuration url

建立url和视图函数之间的对应关系。

2.2 url configuration process

1) In the urls project file contains specific application urls file, and contains the corresponding relationship between the specific url urls file view in the particular application.

2) url configuration items are defined in a list called urlpatterns in which each element is a configuration item, each configuration item calls the url function.

3.url match of the complete process:

  • 1) removing the domain name and the following parameters, left / aIndex, then in front of / removed, the remaining aIndex
  • 2) Take First aindex url.py project file for a matching top to bottom, behind the corresponding processing operation executed after the matching is successful, the matching success is to remove part of a character,
    • Then take the rest urls.py index file to the application's then top to bottom match. --- remove the domain name, the part after the? Also be removed
  • 3) If a match is a view corresponding to the call-generated content returned to the client. If the match fails to produce a 404 error.

4. Error view:

  • 404: Page not found, the debug mode is turned off by default displays a standard error page, if you want to display a custom page, you need the following templates directory, a custom 404.html file.
    • a) url is not configured
    • b) url configuration error
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404错误页面</title>
    <style type="text/css">


    </style>
</head>
<body>
<h1>页面找不到--{{ request_path }}</h1>  
<!--request_path:Django会传过来一个模板变量,包含请求的地址-->
</body>
</html>
  • 500: The server side error can also be custom 500 pages, templates / 500.html.
    a) a view (the views.py) Error
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500错误页面</title>
    <style type="text/css">


    </style>
</head>
<body>
<h1>服务器错误</h1>
</body>
</html>
  • Website developed need to turn off debug mode, in settings.py file:
    • DEBUG=False
    • ALLOWED_HOST=['*']

5. Capture url parameter

进行url匹配时,把所需要的捕获的部分设置成一个正则表达式组,
这样django框架就会自动把匹配成功后相应组的内容作为参数传递给视图函数。
  • 1) position parameters
    • Positional parameters, parameter names can be arbitrary
    from django.conf.urls import url
    from booktest import views
    urlpatterns = [
      url(r'^index$', views.index),   # 首页
      url(r'^showarg(\d+)$', views.showarg),  # 捕获url参数: 位置参数
    ]
from django.http import HttpResponse


def showarg(request, num):  # url中捕获的num必须传入
    return HttpResponse(num)
  • Input http://192.168.1.106:8000/showarg11, to give 11
  • 2) keyword arguments: On the basis of the positional parameters to regular expression group name can be.
    • ? P <Group Name>
    • Keyword arguments, the view parameter name must name the same expression groups and positive --- def showarg (request, num): The num, must be url (r '^ showarg (P? \ D +) $ ', views.showarg), consistent with the url
# urls.py
from django.conf.urls import url
from booktest import views
urlpatterns = [
    url(r'^index$', views.index),   # 首页
    url(r'^showarg(?P<num>\d+)$', views.showarg),   # 捕获url参数:关键字参数
]

6. Log in ordinary cases

  • def index (request): role in the request:
    • Examples of the type of request is HttpRequest object that contains information about the browser request, the request by some properties, can get the information. Django do a layer of packaging
  • 1) shows the login page
    • a) design url, accessed through a browser http://127.0.0.1:8000/login displays the login page when.
    • b) Design of login view function corresponding to url.
    • c) To prepare the template file login.html.
      `` `python

      views.py

      from django.shortcuts import render

Login DEF (Request):
'' 'login page' ''
return the render (Request, 'booktest / the login.html', {})
`` `

# urls.py
from django.conf.urls import url
from booktest import views
urlpatterns = [
    url(r'^index$', views.index),   # 首页
    # url(r'^showarg(\d+)$', views.showarg),  # 捕获url参数: 位置参数
    url(r'^showarg(?P<num>\d+)$', views.showarg),   # 捕获url参数:关键字参数
    url(r'^login$', views.login)    # 显示登录页面
]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <style type="text/css">


    </style>
</head>
<body>
<!--POST:提交的参数在请求头中。-&#45;&#45;数据安全性比较高时,使用post-->

<!--GET:提交的参数在url中。-->
<!--http://192.168.1.106:8000/login_check?username=abc&password=111-->

<!--<form method="get" action="/login_check">-->
<form method="post" action="/login_check">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>
- url   视图      模板文件
- /login    login   login.html
# QueryDict对象的使用方法:
# 赋值: q = QueryDict('a=1&b=2&c=3')
# 取值:两种方式q['a']、q.get('a')
# 直接取没有的值会报错django.utils.datastructures.MultiValueDictKeyError: 'd'
# 但是用q.get('d')就不会报错,会显示没有值(返回None)---可用q.get('d', 'default')的方式,没有时,会返回默认值
>>> from django.http.request import QueryDict
>>> q = QueryDict('a=1&b=2&c=3')
>>> q['a']
'1'
>>> q['b']
'2'
>>> q['c']
'3'
>>> q.get('a')
'1'
>>> q.get('d', 'default')
'default'
# 和dict的本质区别,字典的key唯一,但Querydict允许一个key对应多个value,取多个值时,需要用getlist()方法来获取
>>> q1 = QueryDict('a=1&a=2&a=3&b=4')
>>> q1['a']
'3'
>>> q1.get('a')
'3'
>>> q1.getlist('a')
['1', '2', '3']
  • 2) Log check function
    • a) design url, click on the Login button to initiate the login page to log verification request http://127.0.0.1:8000/login_check.
    • b) Design of login_check view function corresponding to url.
      • Data received form submission over.
      • Log in check, if the correct user name and password to log in successfully jump page. If fails to jump to the login page.
    • c) After a successful login jump to the home page.
      • url view template file
      • /login_check login_check 无
      # urls.py
      from django.conf.urls import url
      from booktest import views
      urlpatterns = [
        url(r'^index$', views.index),   # 首页
        # url(r'^showarg(\d+)$', views.showarg),  # 捕获url参数: 位置参数
        url(r'^showarg(?P<num>\d+)$', views.showarg),   # 捕获url参数:关键字参数
        url(r'^login$', views.login),    # 显示登录页面
        url(r'^login_check$', views.login_check),
      ]
def login_check(request):
    '''登录校验视图'''
    # request.POST  保存的是POST提交的参数-都为QueryDict对象
    # request.GET   保存的是GET提交的参数-都为QueryDict对象 ---直接通过浏览器输入的方式是Get方式
    # 1. 获取提交的用户名和密码---登录的信息,保存在request中
    # print(type(request.POST))   # 后台显示类型为:<class 'django.http.request.QueryDict'>
    username = request.POST.get('username')
    password = request.POST.get('password')
    print(username+':'+password)    # abc:111

    # 2.进行登录的校验
    # 实际开发:根据username和password查找数据库
    # 模拟 abc 111
    if username == 'abc' and password == '111':
        # 正确,跳转到首页
        return redirect('/index')
    else:
        # 错误,跳转到登录页面
        return redirect('/login')

    # 3.返回应答
    # return HttpResponse('ok')

Attributes

  • Unless otherwise indicated below, the properties are read-only.
    • path: a string that represents the full path of the requested page does not contain the domain name or parameter.
    • method: a string that represents the HTTP request method, commonly used values: 'GET', 'POST'.
    • It gives the address in the browser makes a request using get methods, such as hyperlinks.
    • In the browser by clicking the form submit button to initiate a request, if the form's method was set up post request to post.
    • encoding: A string indicating a coding mode data submitted.
    • If None indicates that the default settings using the browser, typically utf-8.
    • This property is writable, you can modify it to access the form encoded data used by modifying, then any access to the property will use the new encoding value.
    • GET: QueryDict type of object, similar to the dictionary, containing all manner of get request parameters.
    • POST: QueryDict types of objects, similar to the dictionary containing all the parameters of the post request mode.
    • FILES: a similar object dictionary that contains all uploaded files.
    • COOKIES: A standard Python dictionary containing all of the cookie, keys and values ​​are strings.
    • session: a subject can read but also write a dictionary-like, represents the current session only when Django enable support sessions available, for details, see "state remains."
    • Run the server, the browser home page in a browser, you can request to see the information in a browser "Developer Tools" in the following figure:

7. Ajax

7.1 Basic Concepts

异步的javascript。在不全部加载某一个页面的情况下(整体刷新--会导致用户体验很差),对页面进行局的刷新,ajax请求,即使出错,也都在后台。
图片,css文件,js文件都是静态文件
  • 1) initiate ajax request: jquery launched
    • Create a / test3 / static / static folder to hold, respectively, and the new / test3 / static / css, / test3 / static / images, / test3 / static / js folder.
      • In the configuration setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]   # 设置静态文件的保存目录
  • 2) implementation of the corresponding view function, returns content json
# views.py
from django.http import HttpResponse, JsonResponse


# /test_ajax
def ajax_test(request):
    '''显示ajax页面'''
    return render(request, 'booktest/test_ajax.html')

def ajax_handle(request):
    '''ajax请求处理'''
    # 返回的json数据{'res':1},JsonResponse会将{'res':1}转换为json数据,返回给浏览器,浏览器中.success(function (data)的data即可接收参数
    return JsonResponse({'res': 1})
  • 3) perform a corresponding callback function. By determining json content, it is treated.

  • The jquery-1.12.4.min.js file in / test3 / static / js / in
    • Use jQuery file:
      • New test3 / templates / booktest / test_ajax.html, <script> Import
<!--test_ajax.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        $(function () {
            // 绑定btnAjax的click事件
            $('#btnAjax').click(function () {
                $.ajax({
                    'url': '/ajax_handle',
                    // 'type': 'get', 默认即为get,可以不写
                    'dataType': 'json'
                }).success(function (data) {    // 执行成功后,会返回data
                    // 进行处理,通过alert取出data中的返回值 res
                    // alert(data.res)
                    if (data.res == 1){
                        $('#message').show().html('提示信息')
                    }
                })

            })
            
        })
    </script>
    <style type="text/css">
        #message {
            dispaly: none;
            color: red;
        }

    </style>
</head>
<body>
<!--点击按钮,页面加载完成后,绑定事件id="btnAjax"-->
<input type="button" id="btnAjax" value="ajax请求">
<div id="message"></div>
</body>
</html>
# urls.py
from django.conf.urls import url
from booktest import views
urlpatterns = [
    url(r'^index$', views.index),   # 首页
    # url(r'^showarg(\d+)$', views.showarg),  # 捕获url参数: 位置参数
    url(r'^showarg(?P<num>\d+)$', views.showarg),   # 捕获url参数:关键字参数
    url(r'^login$', views.login),    # 显示登录页面
    url(r'^login_check$', views.login_check),
    url(r'^test_ajax$', views.ajax_test),
    url(r'^ajax_handle$', views.ajax_handle),   # ajax处理
]
  • In this case the browser does not go to the request page test_ajax, but to request "GET / ajax_handle HTTP / 1.1" 200 10

The concept of asynchronous and synchronous

异步:发起请求后,不等待回调函数[.success(function (data) { }]的执行,代码继续向下走,直到服务器将json传回后,才会继续执行回调函数
同步:ajax也可以发起同步请求,将'async'设置为false
    <script>
        $(function () {
            // 绑定btnAjax的click事件
            $('#btnAjax').click(function () {
                alert(1)
                $.ajax({
                    'url': '/ajax_handle',
                    // 'type': 'get', 默认即为get,可以不写
                    'dataType': 'json',
                    //'async': false, //同步ajax请求,默认true
                }).success(function (data) {    // 执行成功后,会返回data
                    // 进行处理,通过alert取出data中的返回值 res
                    alert(2)
                    // alert(data.res)
                    if (data.res == 1){
                        $('#message').show().html('提示信息')
                    }
                })
                alert(3)
            })
            
        })
    </script>

7.2 Ajax Login Case

- 1)首先分析出请求地址时需要携带的参数。
    - username、password
- 2)视图函数处理完成之后,所返回的json的格式。
    - 登录成功之后的json数据格式{'res':1}、和失败后的json数据格式{'res':0}要做一个设计
    - 通过判断'res'的值,来判断登录是成功还是失败了
  • 1) shows the login page
    • a) design url, accessed through a browser http://127.0.0.1:8000/login_ajax displays the login page when.
    • b) Design of login_ajax view function corresponding to url.

    • c) To prepare the template file login_ajax.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax登录页面</title>
    <style type="text/css">


    </style>
</head>
<body>
<!--<form method="post" action="/login_check">使用ajax的话,就不用表单请求了-->
<div>
    {% csrf_token %}
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    <!--<input type="submit" value="登录">不用表单,则type改为button-->
    <input type="button" id="btnLogin" value="登录">

</div>

<!--</form>-->
</body>
</html>
  • Inside write the code to initiate jquery ajax request.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax登录页面</title>
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        $(function () {
            $('#btnLogin').click(function () {
                // 1.获取username和password
                username = $('#username').val()
                password = $('#password').val()
                // 2.发起post ajax请求,/login_ajax_check,携带用户名和密码
                    $.ajax({
                        'url':'/login_ajax_check',  //需写对应的视图
                        'type': 'post',
                        'data': {'username':username, 'password':password},
                        'dataType': 'json'
                    }).success(function (data) {
                        // 登录成功 {'res':1}   ---跳转到首页
                        // 登录失败 {'res':0}
                        if (data.res == 0){
                            $('#errmsg').show().html('用户名或密码错误')
                        }
                        else{
                            // 跳转到首页
                            location.href = '/index'
                        }
                    })
            })
        })
    </script>
    <style>
        #errmsg{
            display: none;
            color: red;
        }
    </style>
</head>
<body>
<!--<form method="post" action="/login_check">使用ajax的话,就不用表单请求了-->
<div>
    <!--此处会报csrf错误,添加了也不行,暂时注释掉setting.py中csrf处-->
    {% csrf_token %}
    用户名:<input type="text" id="username"><br/>
    密码:<input type="password" id="password"><br/>
    <!--<input type="submit" value="登录">不用表单,则type改为button-->
    <input type="button" id="btnLogin" value="登录">
    <div id="errmsg"></div>
</div>

<!--</form>-->
</body>
</html>
  • 2) Log check function
  • a) design url, click on the Login button to initiate the login page to log verification request http://127.0.0.1:8000/login_ajax_check.
from django.conf.urls import url
from booktest import views
urlpatterns = [
    url(r'^index$', views.index),   # 首页
    # url(r'^showarg(\d+)$', views.showarg),  # 捕获url参数: 位置参数
    url(r'^showarg(?P<num>\d+)$', views.showarg),   # 捕获url参数:关键字参数
    url(r'^login$', views.login),    # 显示登录页面
    url(r'^login_check$', views.login_check),
    url(r'^test_ajax$', views.ajax_test),
    url(r'^ajax_handle$', views.ajax_handle),   # ajax处理
    url(r'^login_ajax$', views.login_ajax), # 显示ajax登录页面
    url(r'^login_ajax_check$', views.login_ajax_check),
]
  • b) Design of login_ajax_check view function corresponding to url.
    • Submit the data received over the post.
    • Log in check, and returns json content. JsonResponse
    • Json format is as follows:
    • { 'Res': '1'} # indicates successful login
    • { 'Res': '0'} # indicates login failure
# /login_ajax_check
def login_ajax_check(request):
    '''ajax登录校验'''
    # 1.获取用户名和密码
    username = request.POST.get('username')    # 不管是表单POST提交,还是ajax-post提交,都放在request.POST中
    password = request.POST.get('password')

    # 2.进行校验,返回json数据
    if username == 'abc' and password == '111':
        # 用户名密码正确
        return JsonResponse({'res': 1})
        # return redirect('/index')   # 如果是ajax返回的页面,不要直接使用redirect,会无法看到index,一直在后台
    else:
        # 用户名或密码错误
        return JsonResponse({'res': 0})

Guess you like

Origin www.cnblogs.com/wangxue533/p/12383663.html