Django学习--docx的网页显示
2019-03-03 本文已影响0人
alue
任务: 上传一个docx文件至web服务器, 如果数据库中没有该文件, web服务器将docx存入数据库, 并且在页面上显示该docx文件
用这个小示例, 熟悉掌握了Django处理用户上传文件的相关操作.最后的效果如下:
![](https://img.haomeiwen.com/i25380/dce2ab46e384a732.png)
![](https://img.haomeiwen.com/i25380/fa59c1b469fef727.png)
![](https://img.haomeiwen.com/i25380/0d01a2da43685ddd.png)
![](https://img.haomeiwen.com/i25380/06438a06d568c9a8.png)
踩到的坑有
- 在模版页面的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 wasPOST
and the<form>
that posted the request has the attributeenctype="multipart/form-data"
. Otherwise,request.FILES
will be empty.
- model里面的file字段的
upload_to
设置为英文路径, 否则总出现编解码错误. - docx转换生成的html字符串, 需要加上
{{ docx_html|safe }}
, 之后才能正确渲染. -
<input type="file" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document" required="" id="id_docx">
可以只显示.docx文件.