'Django admin download data as csv

I want to download data from django admin as .csv file. I followed tutorial https://www.endpoint.com/blog/2012/02/22/dowloading-csv-file-with-from-django.

I didn't see download csv option. How can I solve my problem?

enter image description here

I am using Python3, migration created.

This is my code

models.py

from django.db import models
from django.contrib import admin


class Stat(models.Model):
    code = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    ip = models.CharField(max_length=100)
    url = models.CharField(max_length=100)
    count = models.IntegerField()


class StatAdmin(admin.ModelAdmin):
    list_display = ('code', 'country', 'ip', 'url', 'count')
    def download_csv(self, request, queryset):
        import csv
        f = open('some.csv', 'wb')
        writer = csv.writer(f)
        writer.writerow(["code", "country", "ip", "url", "count"])
        for s in queryset:
            writer.writerow([s.code, s.country, s.ip, s.url, s.count])

admin.site.register(Stat, StatAdmin)


Solution 1:[1]

From Django 3.2 onwards, you also have to register download_csv as an "action". See this link for the official documentation.

Solution 2:[2]

Solution from @Ben works if you want to save the file locally, moreover there is a little mistake< we should open file as 'w', not 'wb' if we are going to write there some strings.

This solution worked for me (you can past it right in your model.Admin subclass, admin class):

def export_as_csv(self, request, queryset):

    meta = self.model._meta
    field_names = [field.name for field in meta.fields]

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
    writer = csv.writer(response)

    writer.writerow(field_names)
    for obj in queryset:
        row = writer.writerow([getattr(obj, field) for field in field_names])

    return response

export_as_csv.short_description = "Export Selected"

and then in model.Admin:

actions = ("export_as_csv",)

Click here to see the source.

Moreover there are some libraries that can do saving files in one click: django-import-export for example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tserg
Solution 2 Artem Chege