Bem vindo!

ao blog Willem Allan

Exportando CSV no admin do django

1) Criar um arquivo na raiz do projeto ou na pasta app com o nome de actions.py
(neste caso está sendo criado dentro de app)

2) Inserir este código no arquivo actions.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf-8 -*-
 
import csv
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
 
 
def export_as_csv(modeladmin, request, queryset):
    """
    Generic csv export admin action.
    """
 
    if not request.user.is_staff:
        raise PermissionDenied
 
    opts = modeladmin.model._meta
    response = HttpResponse(mimetype='text/csv')
    attach = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
    response['Content-Disposition'] = attach
    writer = csv.writer(response)
    field_names = [field.name for field in opts.fields]
 
    # Write a first row with header information
    writer.writerow(field_names)
 
    # Write data rows
    for obj in queryset:
        writer.writerow([getattr(obj, field) for field in field_names])
 
    return response
 
export_as_csv.short_description = "Exportar Cadastros Selecionados como CSV"

3) No admin que deseja que aconteça a exportação, importar o actions.py desta maneira:

1
2
3
4
5
from app.actions import export_as_csv
 
 
class MyAdmin(admin.ModelAdmin):
    actions = [export_as_csv]

Dica de Higor Rossato