问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/41711536/exporting-django-objects-model-in-csv