码迷,mamicode.com
首页 > 其他好文 > 详细

django admin 导出数据简单示例

时间:2018-06-25 13:05:30      阅读:482      评论:0      收藏:0      [点我收藏+]

标签:break   oct   type   spl   attach   ref   position   标签   model   

借鉴博客:https://www.lijinlong.cc/django/djxs/2101.html

具体代码实现:

class TipReport(admin.ModelAdmin):
    actions = [saveexcel]
    list_display = (tiptype, enabled, get_tag,get_content)
    search_fields = (get_tag, tiptype)
    list_per_page = 500

    def get_tag(self, obj):
        if obj.tags.all():
            tag_list = [i.name for i in obj.tags.all()]
            return ,.join(tag_list)
        else:
            return -

    get_tag.short_description = 小贴士标签

    def get_content(self, obj):
        if obj.content:
            return obj.content
        elif obj.image:
            return mark_safe(<a href="%s">%s</a> % (obj.image.url, obj.image.url))
        else:
            return -

    get_content.short_description = 内容

    def saveexcel(self, request, queryset):
        Begin = xlwt.Workbook()
        sheet = Begin.add_sheet(小贴士记录)
        cols = 0
        for query in queryset:
            sheet.write(cols, 0, str(query.tiptype))
            sheet.write(cols, 1, str(query.enabled))
            # for i in unicode(query.tags.all()):
            sheet.write(cols, 2, unicode(query.tags.all()))
            print type(query.content)
            sheet.write(cols, 3, unicode(query.content))

            cols += 1

        Begin.save({}.format("result.xls"))
        def file_iterator(filename, chuck_size=512):
            with open(filename, rb) as f :
                while True:
                    c = f.read(chuck_size)
                    if c:
                        yield c
                    else:
                        break
        response = StreamingHttpResponse(file_iterator({}.format("result.xls")))
        response[Content-Type] = application/octet-stream
        response[Content-Disposition] = attachment;filename="{}".format("result.xls")
        return response
    saveexcel.short_description = 导出数据
admin.site.register(Tip, TipReport)

 

django admin 导出数据简单示例

标签:break   oct   type   spl   attach   ref   position   标签   model   

原文地址:https://www.cnblogs.com/haiyan123/p/9223530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!