以CSV格式导出Django对象模型

以CSV格式导出Django对象模型

本文介绍了以CSV格式导出Django对象模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在django-admin中为管理员创建一个额外的操作.

I want to create an extra action for the admin in django-admin.

我希望能够将数据导出为CSV格式.

I want to be able to export the data as CSV format.

我在admin.py中编写了以下代码:

I have written the following code in my admin.py:

from django.contrib import admin
from .models import News, ResourceTopic, Resource, PracticeTopic, Practice, Contacts, Visualization
import csv
from django.utils.encoding import smart_str
from django.http import HttpResponse
admin.site.register(News)
admin.site.register(ResourceTopic)
admin.site.register(Resource)
admin.site.register(PracticeTopic)
admin.site.register(Practice)
admin.site.register(Visualization)


def export_csv(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;     filename="somefilename.csv"'
    writer = csv.writer(response)
    writer.writerow([
        "First Name",
        "Last Name",
        "Organization",
        "City",
        "Country",
        "Email",
    ])
    for obj in queryset:
        writer.writerow([
            obj.firstName,
            obj.lastName,
            obj.organization,
            obj.city,
            obj.country,
            obj.email,
        ])
     return response

class contactsAdmin(admin.ModelAdmin):
    actions = [export_csv]

admin.site.register(Contacts, contactsAdmin)

我遇到的问题:该文件已下载为download.html.并且该html文件显示了相同的django管理页面.

The problem I have: the file gets downloaded as download.html AND the html file displays the same django admin page.

推荐答案

我正在反过来这样做:

        f = open(file_path, 'wb')
        writer = csv.writer(f)

        #write stuff

        response = HttpResponse(f, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename.csv'
        return response

这篇关于以CSV格式导出Django对象模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:06