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]
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",)
Moreover there are some libraries that can do saving files in one click: django-import-export for example.
- [Django]-How do I make Django admin URLs accessible to localhost only?
- [Django]-JSON Response from Django in Android
1
From Django 3.2 onwards, you also have to register download_csv
as an "action". See this link for the official documentation.
Source:stackexchange.com