文件上传: 1.配置路径 文件上传时,文件数据存储在request.FILES属性中 一般文件都存储到服务器的static目录下的upfile文件夹下 在setting.py文件中配置路径: #静态文件目录 STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] #文件上传目录 MDEIA_ROOT=os.path.join(BASE_DIR,r'static\upfile') 2.定义文件跳转路径 在前台的urls.py文件中配置请求路径: path('upfile/',views.upfile), path('saveFile/',views.saveFile), 3.定义upfile.html文件 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form action="/saveFile/" method="post" enctype="multipart/form-data"> {% csrf_token %} 文件:<input type="file" name="file"/> <input type="submit" name="sbt" value="上传"/> </form> </body> </html> 4.在views.py文件中定义跳转和上传方法 def upfile(request): return render(request,"front/upfile.html") import os from django.conf import settings def saveFile(request): if request.method == 'POST': f = request.FILES['file'] filePath = os.path.join(settings.MDEIA_ROOT,f.name) with open(filePath,'wb') as fp: for info in f.chunks(): fp.write(info) return HttpResponse("上传成功!") else: return HttpResponse("上传失败!") #分页功能 1.定义urls.py path('userList/<pageNum>/',views.userList), 2.定义views.py from .models import UserInfo from django.core.paginator import Paginator def userList(request,pageNum): #获取所有用户 allList = UserInfo.objects.all() #获取分页对象(总数,每页条数) paginator = Paginator(allList,2) page = paginator.page(pageNum) return render(request,"front/userList.html",{"userinfos":page}) 3.定义userList.html页面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>分页功能</title> <style> table{ width:300px; height:200px; border:1px solid grey; border-collapse:collapse; } table td{ width:50px; border:1px solid grey; border-collapse:collapse; } ul li{ float:left; list-style:none; margin-right:10px; } </style> </head> <body> <table> {% for user in userinfos %} <tr> <td>{{ user.id }}</td> <td>{{ user.username }}</td> <td>{{ user.password }}</td> <td>{{ user.sex }}</td> <td>{{ user.age }}</td> <td>{{ user.isDelete }}</td> </tr> {% endfor %} </table> <ul> {% for index in userinfos.paginator.page_range %} <li> <a href="/userList/{{index}}/">{{index}}</a> </li> {% endfor %} </ul> </body> </html>
python-django文件上传和分页功能笔记
猜你喜欢
转载自blog.csdn.net/welun521/article/details/82765870
今日推荐
周排行