Search code examples
djangocsvdjango-adminexport-to-excelexport-to-csv

Exporting Django Objects model in CSV


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.

enter image description here enter image description here


Solution

  • 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