Exporting items from a model to CSV Django / Python

前端 未结 9 2047
死守一世寂寞
死守一世寂寞 2021-02-03 09:52

I\'m fairly new to django and Python and want to be able to export a list of items in my model i.e products. I\'m looking at the documentation here - https://docs.djangoproject.

9条回答
  •  梦毁少年i
    2021-02-03 10:51

    You can also make a template to assist in formatting!

    The template is a common Django template

    from django.template import loader
    def export_to_csv(request):
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename="products-list.csv"'
        template = loader.get_template('templates/products_template.csb')
        response.write(template.render(Context({'products': Products.objects.all()})))
        return response
    

提交回复
热议问题