How to export CSV files in Django – Django Tutorials

How to export CSV files in Django

Hey Guys..! welcome to another Great tutorial. In this tutorial, you will know how to export CSV files in Django. We were well known to download CSV files from different websites. Now its time to implement by our own. so let’s get started.

we are going to implement this concept by scratch. if you don’t know how to start Django project and Django APP, checkout my best tutorials here.

Django tutorial – Build your first App with Django python 3

Django tutorials – how the django project works

To Implement exporting csv files in django, we will follow only 3 steps. Here, they are

  • Create view
  • Creating URL
  • Create Template

Here, you need to configure the code in the views , urls and templates.

Create view for Export CSV files in Django

so lets create a view for exporting CSV, here you need a model which is you are going to export. I took my User model.

Here, i am giving the code of view. i will explain each step below.

import csv
from django.http import HttpResponse
from django.contrib.auth.models import User


def download_csv(request):

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

    writer = csv.writer(response)
    writer.writerow(['Username','Email'])

    users = User.objects.all().values_list('username','email')

    for user in users:
        writer.writerow(user)

    
    return response

we are importing CSV and HttpResponse for creating csv fiels and sending data as http response.

I create a view called download_csv and i created a http respone. we are exporting data to csv, so we used content_type=’text/csv’.

Now, i created a csv writer object and i passed response. And i wrote a row for my columns – [‘Username’, ‘Email’]

I created another object users to get the data from my model User. Now, i wrote the data in the rows using for loop and return the response.

Create a URL for Exporting CSV files in Django

Now create your url.

Note: You need to append this to your urls.

from .views import download_csv
urlpatterns =[
   path('export/',download_csv,name='export'),
]

Create a Template

let’s create a button or link in the template to download the CSV files.

<button type="button"> <a href="{% url 'export' %}">Download CSV</a> </button>

Whenever the user click the Download CSV button then our users.csv will download.

For more details, check out the Django Docs: Outputting CSV with Django

I hope this how to export csv files in Django tutorial helps you. For more interesting Django tutorials subscribe to our newsletter. Thank you.

Leave a Reply