[Django]-Django admin download data as csv

5πŸ‘

βœ…

you need to add download_csv as an action to the StatAdmin class.
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#adding-actions-to-the-modeladmin

def download_csv(modeladmin, 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])


class StatAdmin(admin.ModelAdmin):
    list_display = ('code', 'country', 'ip', 'url', 'count')
    actions = [download_csv]
πŸ‘€Ben

7πŸ‘

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.

πŸ‘€Artem Chege

1πŸ‘

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

πŸ‘€tserg

Leave a comment