Python-Django-Ajax进阶
生活随笔
收集整理的這篇文章主要介紹了
Python-Django-Ajax进阶
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ajax上傳文件:
?
<h2>基于ajax上傳文件</h2><p>名字 <input type="text" id="filename"></p>
<p>文件 <input type="file" id="file"></p>
<button id="filebtn">上傳文件</button>
$('#filebtn').click(function () {
//js取到文件
var myfile=$('#file')[0].files[0]
//生成一個FormData對象
var formdata=new FormData
//放值 //放文件
formdata.append('name',$('#filename').val())
formdata.append('myfile',myfile)
$.ajax({
url:'/fileupload/',
type:'post',
//這兩個要必須寫
processData:false, //不預處理數據 因為FormData 已經做了
contentType:false, //我不指定編碼了 因為FormData 已經做了
data:formdata,
success:function (data) {
console.log(data)
alert(data)
}
})
})
# ajax文件上傳
def fileupload(request):
if request.method == 'GET':
return render(request, 'fileupload.html')
if request.is_ajax():
name = request.POST.get('name')
# 文件對象
myfile = request.FILES.get('myfile')
import os
path = os.path.join('media', name)
with open(path, 'wb') as f:
for line in myfile:
f.write(line)
return HttpResponse('success')
django自帶序列化:
# ajax page,了解,django自帶的序列化def page(request):
if request.method == 'GET':
users = UserInfo.objects.all()
# json序列
# user_dic = [{'name': user.name, 'age': user.age, 'id': user.id} for user in users]
# return JsonResponse(user_dic, safe=False, json_dumps_params={'ensure_ascii': False})
# 顯示結果[{"name": "abc1", "age": 11, "id": 1}, {"name": "ewe", "age": 12, "id": 2}]
# 了解,django自帶的序列化
user_dic = serializers.serialize('json', users)
return HttpResponse(user_dic)
# 顯示結果[{"model": "app01.userinfo", "pk": 1, "fields": {"name": "abc1", "age": 11}}, {"model": "app01.userinfo", "pk": 2, "fields": {"name": "ewe", "age": 12}}]
批量插入數據bulk_create
# 批量插入數據bulk_createdef pagemass(request):
# # objes:對象列表,batch_size 一次插入數據的量
li = []
for i in range(200):
# UserInfo.objects.create() #老大方式
li.append(UserInfo(name='abc%s' % i, age=i + 1))
ret = UserInfo.objects.bulk_create(li, 20)
return HttpResponse('ok')
分頁器組件:
# 分頁器 from django.core.paginator import Paginator def paging(request):users = UserInfo.objects.all().order_by('pk')paginator = Paginator(users, 20)try:currentpage = int(request.GET.get('page', 1)) # 默認顯示第一頁page = paginator.page(currentpage)except Exception as e:# 出錯時顯示第一頁currentpage = 1page = paginator.page(currentpage)# 傳入頁碼數,拿到的就是當前頁對象page = paginator.page(currentpage)# 1 總頁數是否大于11,當總頁碼數大于11if paginator.num_pages > 11:# 1.1 當前頁碼數是否小于6if currentpage <= 6:# 1.1.1 當當前頁碼小于6的時候,就生成11個頁碼數page_range = range(1, 12)# 1.2 當當前頁碼+5 大于等于總頁碼數elif currentpage + 5 >= paginator.num_pages:# 1.2.1 往后推11個頁碼數page_range = range(paginator.num_pages - 10, paginator.num_pages + 1)# 1.3 生成一個左5 右5的區間else:page_range = range(currentpage - 5, currentpage + 6)# 2 總頁碼數不大于11 ,有多少,顯示多少else:page_range = paginator.page_rangereturn render(request, 'page.html', locals()) <table class="table"><thead><tr><th>id</th><th>name</th><th>age</th></tr></thead><br><tbody> {# 循環的時page不是users#}{% for user in page %}<tr><td>{{ forloop.counter }}</td><td>{{ user.name }}</td><td>{{ user.age }}</td></tr>{% endfor %}</tbody></table><nav aria-label="Page navigation"><ul class="pagination">{# 上一頁判斷#}{% if page.has_previous %}<li><a href="/paging/?page={{ page.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">上一頁</span></a></li>{% else %}<li class="disabled"><a href="" aria-label="Previous"><span aria-hidden="true">上一頁</span></a></li>{% endif %}{# 判斷當前頁面是否是循環到的頁碼,如果是,加active#}{% for foo in page_range %}{% if currentpage == foo %}<li class="acitve"><a href="/paging/?page={{ foo }}">{{ foo }}</a></li>{% else %}<li><a href="/paging/?page={{ foo }}">{{ foo }}</a></li>{% endif %}{% endfor %}{# 下一頁判斷#}{% if page.has_next %}<li><a href="/paging/?page={{ page.next_page_number }}" aria-label="Next"><span aria-hidden="true">下一頁</span></a></li>{% else %}<li class="disabled"><a href="" aria-label="Next"><span aria-hidden="true">下一頁</span></a></li>{% endif %}</ul></nav>
forms組件:(數據校驗功能)
<form action=""><p>name <input type="text" name="name"></p><p>pwd <input type="password" name="pwd"></p><p>email <input type="email" name="email"></p><input type="submit"></form><h1>forms的模板渲染之一(推薦)</h1><form action="" method="post" novalidate><p>name: {{ myform.name }}</p><p>pwd: {{ myform.pwd }}</p><p>email: {{ myform.email }}</p><input type="submit"></form><h1>forms的模板渲染之二(推薦!!!!!)</h1><form action="" method="post" novalidate>{% for item in myform %}<p>{{ item.label }}:{{ item }}</p>{% endfor %}<input type="submit"></form><h1>forms的模板渲染之三</h1><form action="" method="post" novalidate>{{ myform.as_p }}<input type="submit"></form> from django import forms # 繼承Form這個類 class MyForm(forms.Form):# 限制name這個字段最長為8,最短為3name=forms.CharField(min_length=3,max_length=8,label='用戶名',required=True,error_messages={'min_length':'至少為3','max_length':'最長為8,您太長了'})pwd=forms.CharField(min_length=3,max_length=8,label='密碼',error_messages={'min_length':'至少為3','max_length':'最長為8,您太長了'})email=forms.EmailField(label='郵箱',error_messages={'invalid':'郵箱格式不合法','required':'這個字段必填'})# ajax register def register(request):if request.method == 'GET':myform=MyForm()return render(request, 'register.html',locals())else:# 生成對象,傳參,傳字典,要校驗數據的字典# myform=MyForm(request.POST)# 自己寫要校驗的字典,數據多了,多的是不校驗的,但是cleaned_data中也沒有多出來的數據# dic={'name':'lqz','pwd':'123','email':'22@qq.com','xx':'xxx'}# dic={'name':'lqz','pwd':'123','email':'22'}# dic = {'name': 'abc', 'pwd': '122', 'email': '5555'}name=request.POST.get('name')pwd=request.POST.get('pwd')email=request.POST.get('email')dic = {'name': name, 'pwd': pwd, 'email': email}print(dic)myform = MyForm(dic)# 所有字典都校驗通過,它就是True的if myform.is_valid():# 取出校驗通過的數據clean_data=myform.changed_dataprint(clean_data)# models.UserInfo.objects.create(**clean_data)else:# 所有的錯誤信息# 只要是校驗通過的值,都在cleaned_data中放著print(myform.changed_data)print(myform.errors.as_data())# 字典類型print(type(myform.errors))print(myform.errors.get('name'))from django.forms.utils import ErrorDictreturn HttpResponse('OK')
ajax總結:
1 默認編碼urlencode,后端按照原來form表單提交的形式取值就可以了()
2 上傳文件,form-data編碼,后端按照原來form表單提交的形式取值就可以了,取數據從POST中取,取文件從FILES中取
3 上傳json格式,django不會處理數據,需要自己處理,自己從body體中取出數據處理
?TTL:
?
?
?
轉載于:https://www.cnblogs.com/du-jun/p/10289775.html
總結
以上是生活随笔為你收集整理的Python-Django-Ajax进阶的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jquery checkbox attr
- 下一篇: 什么是稳压电源