我想在django-admin中为管理员创建一个额外的操作。
我希望能够将数据导出为CSV格式。
我在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)
我遇到的问题:该文件已下载为download.html AND html文件显示相同的django管理页面。
答案 0 :(得分:0)
我反过来这样做:
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