为了实现此功能,需要用到的知识点:
(1)django admin 自定义字段;
参考:http://www.cnblogs.com/wumingxiaoyao/p/6928297.html
(2)使用 docxtpl 模块 对word文档内容 进行替换;
参考:http://www.cnblogs.com/wumingxiaoyao/p/8315814.html
(3)使用django 的 FileResponse 模块 实现文档下载;
参考:http://blog.csdn.net/lmw1239225096/article/details/79047375
主要代码:
url.py:
from django.conf.urls import url
from hys_operation import views
urlpatterns = [
# url(r'^sub_users/(?P<obj_id>\d+)', views.get_sub_users),
# url(r'^sub_servers/(?P<obj_id>\d+)', views.get_sub_servers),
url(r'^download/(?P<paper_num>\w+)', views.download, name='download'),
]
views.py:
from django.http import FileResponse
def download(request, paper_num):
"""
下载数据备案单
:param request:
:param paper_num: 备案单号
:return: 数据流
"""
# file_path = '/webserver/hys_cmdb/static/download/'
file_path = 'E:\\myweb\\hys_cmdb\\static\\download\\'
file = open("{}{}.docx".format(file_path, paper_num), "rb")
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{}.docx"'.format(paper_num)
return response
admin.py:
class DataPaperStoreAdmin(admin.ModelAdmin):
......
def down_paper(self, obj):
"""自定义一个a标签,跳转到实现下载功能的url"""
dest = '{}export/'.format(obj.pk)
title = '下载'
return '<a href="{}">{}</a>'.format(dest, title)
down_paper.short_description = '下载数据单'
down_paper.allow_tags = True
def get_urls(self):
"""添加一个url,指向实现下载功能的函数make_docx"""
from django.conf.urls import url
urls = [
url('^(?P<pk>\d+)export/?$',
self.admin_site.admin_view(self.make_docx),
name='export_data'),
]
return urls + super(DataPaperStoreAdmin, self).get_urls()
def make_docx(self, request, *args, **kwargs):
from docxtpl import DocxTemplate
import re
file_path = 'E:\\myweb\\hys_cmdb\\static\\download\\'
# file_path = '/webserver/hys_cmdb/static/download/'
obj = get_object_or_404(DataPaperStore, pk=kwargs['pk'])
list_nums = re.findall("\d+", obj.paper_num) # 获取字符串中的所有数字
nums = ''.join(list_nums)
doc = DocxTemplate("{}export.docx".format(file_path))
context = {'paper_num': obj.paper_num,
'project_name': obj.project_name,
'to_mail': obj.to_mail,
'data_selected': obj.data_selected,
'start_date': obj.start_date,
'end_date': obj.end_date,
}
doc.render(context)
doc.save("{}{}.docx".format(file_path, nums))
new_path = reverse('download', args=(nums,))
return HttpResponseRedirect(new_path)
list_display = ('project_name', 'to_mail', 'proposer', 'frequency', 'commit_date',
'start_date', 'end_date', 'colored_paper_num', 'is_sure', 'expired', 'down_paper',)
效果: