Exporting Django Objects model in CSV

会有一股神秘感。 提交于 2019-12-25 04:57:12

问题


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

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

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)

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


回答1:


I am doing this the other way round:

        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


来源:https://stackoverflow.com/questions/41711536/exporting-django-objects-model-in-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!