Django补充
django頁面渲染具體流程
在django的頁面渲染中,下面這段程序
def test1(request):return render(request,'aa.html',{'data':'wusir'})等同于
from django.template import loader def test1(request):html = loader.get_template('aa.html')html_str = html.render({'data':'wusir'})return HttpResponse(html_str)django中自定義simple_tag
1、在app目錄下創建一個文件夾名字叫templatetags,名字不能改,在該文件夾下隨便建一個xxx.py文件,寫入以下代碼
from django import template register = template.Library() @register.simple_tag def func(a1,a2): #(參數任意多) ....... 2、在前端頁面的頂部寫上{% load xxx %},然后就可以使用后端所定義的函數{% func 1 2 %}
PS:simple_tag不能作為if后面的判斷條件,但是參數任意多
django中自定義filter
1、在app目錄下創建一個文件夾名字叫templatetags,名字不能改,在該文件夾下隨便建一個xxx.py文件,寫入以下代碼
from django import template register = template.Library() @register.filter def func(a1,a2): #(參數最多兩個) ....... 2、在前端頁面的頂部寫上{% load xxx %},然后就可以使用{ { xxx|func:yyy } } ,xxx,yyy對應兩個參數 ,如果函數只有一個
參數,func后面的冒號和后面的參數就不用寫了。
PS:能作為if后面的判斷條件,但是參數最多兩個,并且冒號后面不能加空格
基于FBV、CBV的用戶認證裝飾器
FBV
def login(request):if request.method == 'GET':return render(request,'login.html')if request.method == 'POST':username = request.POST.get('username')password = request.POST.get('password')obj = User.objects.filter(username=username).first()if not obj:return redirect('/app/login/')if password == obj.pwd:res = redirect('/app/index/')res.set_cookie('username',username)return reselse:return redirect('/app/login/')def auth(func):def inner(request,*args,**kwargs):res = request.COOKIES.get('username')if not res:return redirect('/app/login/')return func(request,*args,**kwargs)return inner@auth def index(request):res = request.COOKIES.get('username')return render(request,'index.html',{'data':res}) views.pyCBV
def login(request):if request.method == 'GET':return render(request,'login.html')if request.method == 'POST':username = request.POST.get('username')password = request.POST.get('password')obj = User.objects.filter(username=username).first()if not obj:return redirect('/app/login/')if password == obj.pwd:res = redirect('/app/index/')res.set_cookie('username',username)return reselse:return redirect('/app/login/')def auth(func):def inner(request,*args,**kwargs):res = request.COOKIES.get('username')if not res:return redirect('/app/login/')return func(request,*args,**kwargs)return innerfrom django import views from django.utils.decorators import method_decorator #三種方式:在每個函數上加,在dispatch上加,在類上加裝飾器 method_decorator(auth,name='dispatch') class Order(views.View):# @method_decorator(auth)# def dispatch(self, request, *args, **kwargs):# return super(Order, self).dispatch(request, *args, **kwargs)# @method_decorator(auth)def get(self,request):res = request.COOKIES.get('username')# if not res:# return redirect('/app/login/')return render(request,'index.html',{'data':res}) views.pydjango之Form組件
django中的Form一般有兩種功能:
- 輸入html
- 驗證用戶輸入
?PS:以后使用的時候將forms改成fields,fields里面有一個插件widget,可以定制樣式
from django import forms from django.forms import fields from django.forms import widgets class FM(forms.Form):user = fields.CharField(error_messages={'required':'用戶名不能為空'},widget=widgets.Textarea(attrs={'class':'c1'}))email = fields.CharField(error_messages={'required':'郵箱不能為空','invalid':'郵箱格式錯誤'},widget=widgets.PasswordInput)pwd = fields.CharField(max_length=12,min_length=6,error_messages={'required':'密碼不能為空','max_length':'最大長度不能超過12','min_length':'最小長度不能低于6'})def test_form(request):if request.method == 'GET':obj = FM()return render(request,'test_form.html',{'obj':obj})elif request.method == 'POST':obj = FM(request.POST)r1 = obj.is_valid()if r1:print(obj.cleaned_data)Person.objects.create(**obj.cleaned_data)else:print(obj.errors)# print(obj.errors.as_json())# print(obj.errors['user'][0])return render(request,'test_form.html',{'obj':obj})return render(request,'test_form.html') views.py?詳細內容參考:https://www.cnblogs.com/wupeiqi/articles/6144178.html
跨站請求偽造
一、簡介
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、普通表單
html中設置Token: {% csrf_token %} View Code2、Ajax請求
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> <form action="/app/test1/" method="post">{% csrf_token %}<input type="text" placeholder="用戶名" name="user"><input type="password" placeholder="密碼" name="pwd"><input type="submit" value="提交"><input id="btn" type="button" value="按鈕"> </form><script src="/static/jquery-1.12.4.js"></script> <script src="/static/jquery.cookie.js"></script> <script>$('#btn').click(function () { {# 給除GET|HEAD|OPTIONS|TRACE幾個方法以外的方法全部設置csrftoken#} {# 過濾方法#}var csrftoken = $.cookie('csrftoken');function csrfSafeMethod(method) {return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));} {# 設置csrftoken#}$.ajaxSetup({beforeSend: function(xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {xhr.setRequestHeader("X-CSRFToken", csrftoken);}}});$.ajax({url:'/app/test1/',type:'GET',data:{'user':'alex'}, {# headers: {'X-CSRFtoken': $.cookie('csrftoken')}, 單個ajax請求設置csrftoken#}success:function (res) {}})}) </script></body> </html> View Code轉載于:https://www.cnblogs.com/wusir66/p/10183079.html
總結
- 上一篇: 微信小程序——开篇
- 下一篇: k-means 聚类过程演示