django admin 中实现word文档下载

为了实现此功能,需要用到的知识点:

(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',)

  

效果:

 

转载于:https://www.cnblogs.com/wumingxiaoyao/p/8317548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值