D
D
Denis Michurin2017-11-29 17:21:08
Django
Denis Michurin, 2017-11-29 17:21:08

Import data from model to csv Django?

Dear experts, please tell me how to generate csv from a model in Django and give it to the client?
Reached this place, and then blunt. Tell good people

@login_required()
def generate_csv(request):
    file = 'inventory.csv'
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="%s"' % file
    equipment = Equipment.objects.filter(is_active=True)
    writer = csv.writer(response)
    ...
    return response

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sergeev, 2017-11-29
@denistu10

@login_required()
def generate_csv(request):
    file = 'inventory.csv'
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="%s"' % file
    equipment = Equipment.objects.filter(is_active=True)
    writer = csv.writer(response, delimiter=';')
    for eq in equipment:
        writer.writerow([eq.field_1, eq.field_2, ...])
    return response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question