how to generate a csv of users in Django?


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 = []
    for p in perfiles:
        columnas = [p.usuario.username,p.usuario.first_name,p.usuario.last_name,,]
    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

1 answer


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