Django-import-export outside Admin

Asked

Viewed 80 times

0

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

I tried to

I am trying to export tables to Excel using Django-import-export outside of Admin, that is, in a template. See that in /person/ there is a button to export. This time I created a little project just for that.

So check out my latest commit

https://github.com/rg3915/dj-export/commit/43d7a8cdc719c78a5b83bf91eaed1d635c48ce6a

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 on the button gave the following error:

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

How do I solve this problem?

I am managing to evolve 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 it still remains to convert the bytes to download, as it gave the following error:

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

1 answer

0


Solved:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.