任务: 上传一个docx文件至web服务器, 如果数据库中没有该文件, web服务器将docx存入数据库, 并且在页面上显示该docx文件
用这个小示例, 熟悉掌握了Django处理用户上传文件的相关操作.最后的效果如下:




踩到的坑有
- 在模版页面的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文件.
网友评论