python 提升生活和办公效率

Django学习--docx的网页显示

2019-03-03  本文已影响0人  alue

任务: 上传一个docx文件至web服务器, 如果数据库中没有该文件, web服务器将docx存入数据库, 并且在页面上显示该docx文件

用这个小示例, 熟悉掌握了Django处理用户上传文件的相关操作.最后的效果如下:


简单的上传界面 候选项只有.docx文件 点击上传后,自动跳转到docx生成的html页面, 并且存入数据库
如果再次提交相同的docx文件,则给出提示

踩到的坑有

  1. 在模版页面的form表单,要添加这些 <form method="post" enctype="multipart/form-data"> {% csrf_token %} </form>, 之后就能在request.FILES获取提交的文件了
    官方文档给过提醒如下:

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

  1. model里面的file字段的upload_to设置为英文路径, 否则总出现编解码错误.
  2. docx转换生成的html字符串, 需要加上{{ docx_html|safe }}, 之后才能正确渲染.
  3. <input type="file" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document" required="" id="id_docx"> 可以只显示.docx文件.
上一篇下一篇

猜你喜欢

热点阅读