The list thats being displayed can be downloaded as a CSV file by modifying the ModelAdmin code.
import csv
from django.http import HttpResponse
from django.utils.text import slugify
@admin.register(Note)
class NoteAdmin(admin.ModelAdmin):
list_display = ('pk','title', 'description')
search_fields = ('title', 'description')
list_editable = ('title','description',)
def export_as_csv(self, request, queryse1t, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = f'attachment; filename={slugify(queryset.model.__name__)}-export.csv'
writer = csv.writer(response)
fields = [field.name for field in queryset.model._meta.fields]
writer.writerow(fields)
for obj in queryset:
row = [getattr(obj, field) for field in fields]
writer.writerow(row)
return response
export_as_csv.short_description = "Export as CSV"
def get_actions(self, request):
actions = super().get_actions(request)
actions['export_as_csv'] = (self.export_as_csv, 'export_as_csv', "Export selected %(verbose_name_plural)s as CSV")
return actions
This export_csv
function takes all the fields that are present in the model and then writes those in a CSV file. After creating a function to download the data, we must add it in the actions dropdown in our admin page, which can be done by modifying the get_actions
and linking it with our function.
After the code, is added there would be an extra option in the actions
dropdown in the admin page, which will allow the user to download the selected notes as a CSV file.
On clicking the go button, the selected notes data would be downloaded as a CSV file.
Here, all the fields have been included in the csv file, you can further restrict the fields by modifying the export_csv
function to include only the field names that you want.
For example,
def export_as_csv(self, request, queryse1t, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = f'attachment; filename={slugify(queryset.model.__name__)}-export.csv'
writer = csv.writer(response)
fields = ['id', 'title']
writer.writerow(fields)
for obj in queryset:
row = [getattr(obj, field) for field in fields]
writer.writerow(row)
return response
export_as_csv.short_description = "Export as CSV"
The above code will download the CSV file with only the id and title fields. Similarly, fields may be modified the way you want, when you don't want some sensitive information to get downloaded as CSV file such as passwords.