django-import-export outside Admin

0

Does anyone know how I would use django-import-export outside Admin? That is, I wanted the export button of this library in a template of mine, outside Admin. Which way to the stones?

I've tried

I'm trying to export tables to Excel using django-import-export outside Admin, or either in a template. Notice that in / person / has a button to export. This time I created a design just for that.

See my latest commit

from import_export.admin import ExportMixin

def export_data_person(request):
    e = ExportMixin()
    file_format = 'XLSX'
    queryset = Person.objects.all()
    return e.get_export_data(file_format, queryset)

And when I clicked the button gave the following error:

AttributeError at /person/export/
'ExportMixin' object has no attribute 'model'

How do I resolve this problem?

I'm getting evolved in the solution

def export_data_person(request):
    e = ExportMixin()
    e.model = Person
    file_format = XLSX()
    queryset = Person.objects.all()
    return e.get_export_data(file_format, queryset)

But you still have to convert the bytes to download, because it gave the following error:

AttributeError at /person/export/
'bytes' object has no attribute 'get'
    

asked by anonymous 09.08.2016 / 22:23

1 answer

0

Resolved:

def export_data_person(request):
    queryset = Person.objects.all()
    return _export_data(queryset, 'person')


def export_data_person_blocked(request):
    queryset = Person.objects.filter(blocked=True)
    return _export_data(queryset, 'person-blocked')


def _export_data(queryset, filename_prefix):
    e = ExportMixin()
    e.resource_class = PersonResource
    e.model = Person
    data = e.get_export_data(XLSX(), queryset)
    mdata = datetime.now().strftime('%Y-%m-%d')
    response = HttpResponse(
        data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = 'attachment; filename="{0}-{1}.xlsx"'.format(filename_prefix, mdata)
return response
    
14.09.2016 / 21:41