1. 程式人生 > >Django中級篇(上)

Django中級篇(上)

[0 新頁面 cor except setup png int ros action

Form驗證

django中的Form一般有兩種功能:

  • 輸入html-----------不能你自己寫一些標簽,而幫你自動生成
  • 驗證用戶輸入-------將用戶驗證信息保存起來,可以傳到前段
技術分享 View 技術分享 form.html 技術分享 froms

-----------------------------------總結:-----------------------------------------

1、<form action="/from1/" method="post">中url必須要包括在/xxx/中間,因為,無論你在路由中有沒有寫最後的/在跳轉的時候,瀏覽器都會為你自動加上,所以你必須加上,不然會報錯

2、input標簽你自己可以在html中創建,也可以利用djanjo創建,利用djanjo創建的好處是,當你在input標簽中寫入數據後,提交刷新頁面的時候,數據還存在,因為在你寫的f1 = Form1(request.POST)中已經存在你所輸入的數據

3、在render(requset,{})中傳參數的時候,既可以用local()進行傳遞,又可以用字典進行傳遞

4、後臺獲取數據的時候,不能通過索引進行取值,例f[‘user‘]會報錯,應該通過 . 進行獲取值

5、request.method == ‘POST‘ 其中的POST,必須大寫,不然會報錯

一、forms.CharField()中參數總結

required=False   ---------------------------------------------------------------------------------------------------------------可以為空,默認為Ture不能為空

max_length=10 ---------------------------------------------------------------------------------------------------------------最多10個字符

mix_length=10 ---------------------------------------------------------------------------------------------------------------最少10個字符

error_messages={‘required‘:‘用戶名不能為空‘,‘min_length‘:‘標題最少為5個字符‘,‘max_length‘:‘標題最多為20個字符‘}----自定義錯誤信息

widget=forms.TextInput()--------------------------------------------------------------------------------------------------------默認是input標簽

widget=forms.Textarea()----------------------------------------------------------------------------------------------------------文本標簽

...........

widget=forms.TextInput(attrs={‘class‘: "form-control", ‘placeholder‘: ‘郵箱‘}),------------------------------------為標簽設置class屬性以及顯示

==============================================================================================

下拉框,參數choices=xxx是固定格式,參數a的形式必須寫成下面這種形式,當我們往數據庫中添加數據的時候,在不從新啟動服務的情況下,下拉框中的數據不會更新,因為類下的靜態字段只創建一次,創建對象只執行__init__方法,所以必須在創建對象執行__init__方法的時候再一次執行一下靜態字段就可以達到更新的目的

a = (

  (6,‘乒乓球‘),

  (1,‘足球‘),

  (2,‘籃球‘),

  (3,‘手球‘),

)

forms.CharField( widget=forms.Select(choices=a) )

技術分享

自定制驗證規則:

自己可以自定義驗證規則,加到裏面

from django.core.exceptions import ValidationError
from django import forms
import re
def mobile_validate(value):
    mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘)
    if not mobile_re.match(value):
        raise ValidationError(‘手機號碼格式錯誤‘)
pwd = forms.CharField(validators=[mobile_validate, ],
                    
                    error_messages={‘required‘: u‘手機不能為空‘},
                    widget=forms.TextInput(attrs={‘class‘: "form-control",‘placeholder‘: u‘手機號碼‘}))
技術分享 Form

Cookie

1、設置及獲取Cookie:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render,HttpResponse

def form1(request):
    print(request.COOKIES)
    print(request.COOKIES[‘k9‘])  #如果沒有的話會報錯
    print(request.get_signed_cookie(‘k3‘,salt=‘alex‘,default=None))  #獲取的時候也得加salt

    rep = HttpResponse(‘GHHG‘)

    rep.set_cookie(‘k1‘,1213)
    rep.set_signed_cookie(‘k3‘,456,salt=‘alex‘,)
    return rep
request.COOKIES[‘key‘]

request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)

    參數:

        default: 默認值

           salt: 加密鹽

        max_age: 後臺控制過期時間

2、設置Cookie:

rep = HttpResponse(...) 或 rep = render(request, ...)

rep.set_cookie(key,value,...)

rep.set_signed_cookie(key,value,salt=‘加密鹽‘,...)

    參數:

        key,              鍵

        value=‘‘,         值

        max_age=None,     超時時間

        expires=None,     超時時間(IE requires expires, so set it if hasn‘t been already.)

        path=‘/‘,         Cookie生效的路徑,/ 表示根路徑,特殊的:跟路徑的cookie可以被任何url的頁面訪問

        domain=None,      Cookie生效的域名

        secure=False,     https傳輸

        httponly=False    只能http協議傳輸,無法被JavaScript獲取(不是絕對,底層抓包可以獲取到也可以被覆蓋)

max_age=None, 後面直接寫時間就可以了

expires=None , 必須寫獲取當前時間,再設置以當前時間為準,多長時間後失效 expires= time.time() + 10

由於cookie保存在客戶端的電腦上,所以,JavaScript和jquery也可以操作cookie。

<script src=‘/static/js/jquery.cookie.js‘></script>

$.cookie("list_pager_num", 30,{ path: ‘/‘ });

Session

Django中默認支持Session,其內部提供了5種類型的Session供開發者使用:

  • 數據庫(默認)
  • 緩存
  • 文件
  • 緩存+數據庫
  • 加密cookie

1、數據庫Session

技術分享 數據庫Session

2、緩存Session

技術分享 緩存Session

3、文件Session

技術分享 文件Session

4、緩存+數據庫Session

技術分享 緩存+數據庫Session

5、加密cookie Session

技術分享 Session用戶驗證

擴展:Session用戶驗證(裝飾器)

    def login(func):
        def wrap(request, *args, **kwargs):
            # 如果未登陸,跳轉到指定頁面
            if request.session[‘is_login‘]:
                return redirect(‘http://www.baidu.com‘)
            return func(request, *args, **kwargs)
        return wrap
    return  HttpResponse(‘GHHG‘)

跨站請求偽造(csrf)

一、簡介

如果在配置中加入 ‘django.middleware.csrf.CsrfViewMiddleware‘, post請求就會開啟驗證,如果為驗證通過,post請求不會通過,如果想通過驗證,就在html的body部分加入

{% csrf_token %}--------------->第一次get請求的時候,會隨機生成一個具有驗證功能的字符串,當我們通過post方式進行請求的時候,就會通過驗證

django為用戶實現防止跨站請求偽造的功能,通過中間件 django.middleware.csrf.CsrfViewMiddleware 來完成。而對於django中設置防跨站請求偽造功能有分為全局和局部。

全局:

  中間件 django.middleware.csrf.CsrfViewMiddleware

局部:

  • @csrf_protect,為當前函數強制設置防跨站請求偽造功能,即便settings中沒有設置全局中間件。
  • @csrf_exempt,取消當前函數防跨站請求偽造功能,即便settings中設置了全局中間件。

註:from django.views.decorators.csrf import csrf_exempt,csrf_protect

二、應用

1、普通表單

veiw中設置返回值:

  return render_to_response(‘Account/Login.html‘,data,context_instance=RequestContext(request))  

     或者
     return render(request, ‘xxx.html‘, data)
html中設置Token:   {% csrf_token %} 

2、Ajax

對於傳統的form,可以通過表單的方式將token再次發送到服務端,而對於ajax的話,使用如下方式。

view.py

from django.template.context import RequestContext

# Create your views here.

def test(request):

    if request.method == ‘POST‘:

        print request.POST

        return HttpResponse(‘ok‘)

    return  render_to_response(‘app01/test.html‘,context_instance=RequestContext(request))

text.html

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title></title>

</head>

<body>

    {% csrf_token %}

    <input type="button" onclick="Do();"  value="Do it"/>

    <script src="/static/plugin/jquery/jquery-1.8.0.js"></script>

    <script src="/static/plugin/jquery/jquery.cookie.js"></script>

    <script type="text/javascript">

        var csrftoken = $.cookie(‘csrftoken‘);

  

        function csrfSafeMethod(method) {

            // these HTTP methods do not require CSRF protection

            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

        }

        $.ajaxSetup({

            beforeSend: function(xhr, settings) {

                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {

                    xhr.setRequestHeader("X-CSRFToken", csrftoken);

                }

            }

        });

        function Do(){

            $.ajax({

                url:"/app01/test/",

                data:{id:1},

                type:‘POST‘,

                success:function(data){

                    console.log(data);

                }

            });
        }

    </script>

</body>

</html>

Django中級篇(上)