码迷,mamicode.com
首页 > Web开发 > 详细

Django文件的上传和数据显示

时间:2019-10-03 20:01:08      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:request   ==   load   文件中   执行   BMI   修改   orm   enc   

前言

最近在做基于机器学习的预测系统,里面需要用到excel表格的上传和显示,在这把过程记录一下

Excel文件的上传

  1. 在页面中加入form表单

    <form method="POST" action="/index/" enctype="multipart/form-data">
      {% csrf_token %}
        <input class="form-control-file" type="file" name="Scores" accept=".xlsx, .xls"/>
        <input class="form-control-file" type="submit" value="上传"/>
        {% if msg %}
          <span>
            {{msg}}
          </span>
        {% endif %}
    </form>
  2. 修改应用文件夹中views.py文件

    首先导入用到的库

    from os.path import isdir, dirname, join
    from os import mkdir
    from .settings import BASE_DIR

    接着增加上传函数

    def upload(request):
        if request.method == 'POST':
            # 创建用来存储上传文件的文件夹
            uploadDir = BASE_DIR+'/upload'
            if not isdir(uploadDir):
                mkdir(uploadDir)
            # 获取上传的文件
            uploadedFile = request.FILES.get('Scores')
            if not uploadedFile:
                return render(request, 'index.html', {'msg':'没有选择文件'})
            if not uploadedFile.name.endswith('.xlsx'):
                if not uploadedFile.name.endswith('.xls'):
                    return render(request, 'index.html', {'msg':'必须选择xlsx或xls文件'})
            # 上传
            dstFilename = join(uploadDir, uploadedFile.name)
            with open(dstFilename, 'wb') as fp:
                for chunk in uploadedFile.chunks():
                    fp.write(chunk)
            context = {}
            context['msg'] = '上传成功'
            return render(request, 'index.html', context)
        else:
            return render(request, 'index.html',{'msg':None})
  3. 修改应用文件夹中的urls.py文件

    urlpatterns = [
     path('index/', views.upload,),
     path('admin/', admin.site.urls),
    ]

Excel文件的读取与显示

  1. 首先在views.py文件中添加需要用到的库

    import pandas as pd

    接着修改刚才的上传函数

    def upload(request):
     if request.method == 'POST':
         # 创建用来存储上传文件的文件夹
         uploadDir = BASE_DIR+'/upload'
         if not isdir(uploadDir):
             mkdir(uploadDir)
         # 获取上传的文件
         uploadedFile = request.FILES.get('Scores')
         if not uploadedFile:
             return render(request, 'index.html', {'msg':'没有选择文件'})
         if not uploadedFile.name.endswith('.xlsx'):
             if not uploadedFile.name.endswith('.xls'):
                 return render(request, 'index.html', {'msg':'必须选择xlsx或xls文件'})
         # 上传
         dstFilename = join(uploadDir, uploadedFile.name)
         with open(dstFilename, 'wb') as fp:
             for chunk in uploadedFile.chunks():
                 fp.write(chunk)
         # 读取excel文件并转化为html格式
         pdData = pd.read_excel(dstFilename)
         pdhtml = pdData.to_html()
         context = {}
         context['form'] = pdhtml
         context['msg'] = '上传成功'
         return render(request, 'index.html', context)
     else:
         return render(request, 'index.html',{'msg':None})
  2. 最后在页面中增加

     {% autoescape off %}
        {{form}}
     {% endautoescape %}
  3. 执行命令,运行服务器,即可上传文件并且将上传的Excel表格显示在网页中了

Django文件的上传和数据显示

标签:request   ==   load   文件中   执行   BMI   修改   orm   enc   

原文地址:https://www.cnblogs.com/FortisCK/p/11620250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!