目錄:
1、URL
2、Models
- 操作
3、Templates
- html模板的使用
- 自定義函數
4、cookie和session
5、分頁(自定義分頁)
6、Form驗證
內容:
1、URL
默認值:
urls.pyView Code
url(r'^index/', views.index, {'name': 'root'}),
views.py
def index(request,name):
print(name)
return HttpResponse('ok')
命名空間:
namespace是添加在name前面,和name結合一起生成URL的方法
#urls.py中View Code
from django.conf.urls import url,include
urlpatterns = [
url(r'^a/',include('app01.urls',namespace='author')),
]
#app01的urls.py中
from django.conf.urls import url
from app01 import views
app_name = 'app01'
urlpatterns = [
url(r'^index/',views.index, name='index'),
]
#app01的views中
def index(request):
v = reverse('author:index')
print(v)
return HttpResponse('ok')
備注:
模板語言中需要{% url 'author:index' %}
請求周期:
url -> 路由->函數或者類-> 返回字符串或者模板語言
Form表單提交:
提交-> url->函數或者類中的方法處理,處理完畢后返回給用戶:
HttpReponse()或者render()或者redirect()無論哪種方法,最后提交給用戶的都是已經處理過的頁面
用戶看到的永遠都是已經處理完成的界面,當接受到redirect時自動發起一個新的URL
Ajax:
$.ajax({
url:'/index/',
data:{'k':'v'},
dataType: 'JSON',
type: 'POST',
traditional: true,
success: function(data){
location.reload() #刷新
locatin.href='某個地址' #跳轉
}
})
提交 -> url -> 函數或者類中的方法
HttpResponse()
render(request, 'index.html',{'k':'v'})
生成字符串返回給用戶
2、Views
請求的其他信息
3、Models
- 操作
3、Templates
- html模板的使用
a) 在模板中定義:
{% block content %} {% endblock %}
b) 在其他html中:
最上面定義:
{% extends ‘模板頁名稱’%}
{% block content %}
自定義內容
{% endblock %}
備注:
由於css和js每個網頁有可能會修改,所以需要修改:
1、在</style>下面寫{% block css %}{% endblock%}
2、在</script>下面寫{% block js%}{% endblock%}
這樣在子版調用可以分別設置
母版html類型:
1、extends: 每個模板的繼承,只能繼承一個模板
2、include: {% include ‘tag-name’%} #可以定義多個並可重復調用
- 自定義函數(自定義simple tag) 自定義函數也是在模板里使用的方法
simple_tag:
a、在某個app里創建一個templatetags目錄,名字不能改
b、在這個目錄下創建一個任意py文件
c、在這個文件中導入:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
d、創建函數:
def func(a1,a2,a3...):
return 'abc'
e、settings文件中注冊APP
f、html文件中頂部{% load '該py文件' %}
g、html引用{% 函數名 arg1 arg2 arg* %}#使用時必須使用該方式調用
filter:
filter與simpe_tag比較:
1、filter與simple_tag定義類似,所以a-b步驟一樣,c步驟中@register.simple_tag需要改成@register.filter
2、在html中調用,filter最多只能調用兩個參數,同時方法為{{ ‘參數1’|函數名:'參數二' }}中間連空格都沒法添加,或者{{ ‘參數1’|函數名:數字 }}形式
3、filter可以在{%if ‘參數1’|函數名:'參數二' %}{% endif%} filter可以作為if條件來操作
4、cookie和session
1、cookie:
cookie是保存在用戶瀏覽器的一個鍵值對,用來記錄用戶登錄信息
def login(request):
當用戶名密碼核對成功后:
res = redirect('/index/')#將跳轉到index界面
res.set_cookie('name': username) #設置cookie值
def index(request):
cookie = request.COOKIES.get('name') #獲取cookie
if not cookie:
return redict(‘/login/’)#如何cookie沒有獲取到就要跳轉會login界面
return render(request,'index.html',{'current_name': cookie}) #這樣可以顯示誰登錄了
cookie能提供的功能:
從請求中獲取cookie:cookie是已字典的形式存在
1、request.COOKIE[‘username’]
2、request.COOKE.get(‘username’)
生成cookie:
1、設置cookie,關閉瀏覽器就失效
response.set_cookie(‘key’,'value')
return response
2、cookie參數:
key, 鍵
value=‘’, 值
max_age=None, 超時時間
expires=None 超時時間(IE requires expires, so set it if hasnt;t been already)
path='/', cookie生效的路徑,/表示根路徑,特殊的:根路徑cookie可以被任何url頁面訪問,如果寫成別的路徑,比如/index表示只能在index的url中使用
domain=None, cookie生效域名
secure=False https傳輸
httponly=False 只能http協議傳輸,無法被JavaScript獲取(不是絕對,底層抓包可以獲取到也可以被覆蓋)
由於cookie保存再客戶端的電腦上,所以JavaScript和jquery也可以操作cookie
<script src='/static/js/jquery.cooki.js'></script>
$.cookie('list_pager_num',30,{path: '/'});
例子:
1、response.set_cookie(‘key’,'value',max_age=10)#設置cookie在10s后失效
2、import datetime
current_date = datetime.datetime.utcnow()
current_date += datetime.timedelta(seconds=10)
response.set_cookie(‘key’,'value',expires=current_date)
3、response.set_cookie(‘user_type’,'abcabd',httponly=True)#設置后沒法通過js抓取到該cookie
4、juery-cookie:
下載jquery-cookie.js文件:由於它是jquery的插件,用的時候必須放在jquery下面
網址:plugins.jquery.com/cookie
$.cookie('k1','v1') 設置值
$.cookie('k1') 獲取值
$.cookie('k','v',{'path':})
通過cookie完成頁面顯示條目數功能:
<body>View Code
<ul>
{% for item in li %}
<li>{{ item }}</li>
{% endfor %}
{{ page_str }}
</ul>
<div>
<select id="ps" onchange="changePageSize(this)">
<option value="10">10</option>
<option value="30">30</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function () {
var v = $.cookie('per_page_count'); /* 頁面重新加載后獲取該值,然后讓select的val加載該值*/
$('#ps').val(v)
})
function chanagePageSize(ths) {
var v = $(ths).val();
$.cookie('per_page_count',v,{path: '/user_list'})
location.reload()
}
</script>
</body>
def user_list(request):View Code
val = request.COOKIES.get('per_page_count')
val = int(val) #該值必須為整數
設置cookie可以使用密文設置:
obj = HttpResponse('s')
obj.set_signed_cookie('username','hahaha',salt='abcabcabd') #設置cookie為密文
獲取cookie解密:
request.get_signed_cookie('username',salt='abcabcabd')
裝飾器:
- FBV:
def auth(func):View Code
def inner(*args,**kwargs):
v = request.COOKIES.get('usernmae')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner
@auth
- CBV
def auth(func):只對get方法做認證
def inner(*args,**kwargs):
v = request.COOKIES.get('usernmae')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner
from django import views
from django.utils.decorators import method_decorator
class Order(views.View):
@method_decorator(auth) #只對get方法做認證
def get(self,request):
pass
def post(self,request):
def auth(func):CBV裝飾器方法一
def inner(*args,**kwargs):
v = request.COOKIES.get('usernmae')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispath')
class Order(views.View):
def get(self,request):
pass
def post(self,request):
pass
def auth(func):CBV裝飾器方法二
def inner(*args,**kwargs):
v = request.COOKIES.get('usernmae')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner
from django import views
from django.utils.decorators import method_decorator
class Order(views.View):
@method_decorator(auth)
def dispatch(self, request, *args, **kwargs):
return super(Order, self).dispatch(request,*args,**kwargs)
def get(self,request):
pass
def post(self,request):
pass
5、分頁(自定義分頁)
防止XSS攻擊:默認情況下django只會認為后端傳遞過來的是字符串,所以html標記、js語言全部當做字符串來處理
為了讓django可以接受html或者js語言,可以使用:
1、前端方法:使用filter: {{ str|safe }} //通過safe在前端將html、js轉換
2、后端方法:引用 from django.utils.safestring import mark_safe,然后將自定義字符串通過mark_safe方法進行處理
6、Form驗證
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。