how to generate a csv of users in Django?

2

I have a problem trying to generate a CSV file with all registered users to export it.

def descargar_usuarios(request):
perfiles = Perfil.objects.all()
response = HttpResponse(content_type='application/csv')
with open('usuarios.csv','wb') as f:
    writer = csv.writer(f)
    columnas = []
    writer.writerows(['usuario','nombre','apellido','correo','boutique'])
    for p in perfiles:
        columnas = [p.usuario.username,p.usuario.first_name,p.usuario.last_name,p.usuario.email,p.boutique]
        writer.writerows(columnas)
    writer.save(response)
    return response

I try to write all the columns at once but I can not find the way.

Once you have it, I do not want to save it on the server, but download it from the browser.

    
asked by F Delgado 05.03.2018 в 11:53
source

1 answer

2

to download a csv not only you have to specify the content_type, but also the header.

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

with this you will download it in the browser

You can see more details on the official documentation

    
answered by 05.03.2018 / 12:04
source