How to Export CSV File in Django with Examples

Django, a high-level Python web framework, is widely used for building web applications. One common requirement in web applications is exporting data to CSV (Comma-Separated Values) files. Whether you need to provide users with downloadable reports or backup data, exporting to CSV is a convenient and widely supported option. In this tutorial, we’ll walk you through the process of exporting data to a CSV file using Django with practical examples.

Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  1. Python (3.6 or higher)
  2. Django
  3. A Django project with data to export. You can refer to our Blog.

Export CSV using Django Views

Django view that will handle the export functionality

Step 1: Create a Django View for Exporting Data

To start, let’s create a Django view that will handle the export functionality. We’ll assume you already have a Django project set up. If not, you can create one using django-admin or django-admin startproject.

In your Django app, create a new view function in your views.py file:

# myapp/views.py

from django.http import HttpResponse
import csv

def export_csv(request):
    # Your data retrieval logic goes here
    data = [
        ['Name', 'Age', 'Email'],
        ['John Doe', 30, '[email protected]'],
        ['Jane Smith', 25, '[email protected]'],
        # Add your data here
    ]

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

    writer = csv.writer(response)
    for row in data:
        writer.writerow(row)

    return response

In this example, we’ve created a simple data list containing a header row and some sample data. Replace this with your data retrieval logic.

Step 2: Create a URL Pattern for the Export View

Next, add a URL pattern for the export view in your app’s urls.py file:

# myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    # Other URL patterns
    path('export-csv/', views.export_csv, name='export_csv'),
]

This URL pattern maps the /export-csv/ URL to the export_csv view we created earlier.

Step 3: Create a Template for the Export Download Button (Optional)

You may want to provide a button or link on a web page that triggers the CSV export. To do this, create an HTML template with a download link to the export view. Here’s an example:

<!-- templates/export_button.html -->

<a href="{% url 'export_csv' %}">Export to CSV</a>

Now, include this template in your desired web page using Django’s {% include %} tag.

Step 4: Run Your Django Development Server

Before you can test the export functionality, make sure your Django development server is running:

python manage.py runserver

Step 5: Access the Export View

Now that everything is set up, you can access the export view by visiting the following URL in your web browser:

http://localhost:8000/export-csv/

Clicking this link will trigger the CSV export functionality, and your browser will prompt you to download the exported_data.csv file.

Congratulations! You’ve successfully exported data to a CSV file using Django.

Exporting a Django QuerySet to CSV

To export data from a Django QuerySet to a CSV file, follow these steps:

Step 1: Create a Django Model

Let’s assume you have a Django model named Person:

# models.py

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    email = models.EmailField()

Step 2: Export Data to CSV

Now, export the QuerySet data to a CSV file:

# views.py

from django.http import HttpResponse
import csv
from .models import Person

# views.py

def export_query_to_csv(request):
    data = Person.objects.all()

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

    writer = csv.writer(response)
    writer.writerow(['Name', 'Age', 'Email'])  # CSV header

    for person in data:
        writer.writerow([person.name, person.age, person.email])

    return response

Step 4: Define URL Pattern

Add a URL pattern for this export view in your app’s urls.py:

# myapp/urls.py

urlpatterns = [
    # Other URL patterns
    path('export-query-to-csv/', views.export_query_to_csv, name='export_query_to_csv'),
]

Now, accessing /export-query-to-csv/ will trigger the export of the Person model data to a CSV file.

Exporting HTML Table to CSV

Sometimes, you may want to export data displayed in an HTML table to a CSV file. Here’s how you can achieve this:

Step 1: Create an HTML Table

Assume you have an HTML template that displays data in a table:

<!-- templates/data_table.html -->

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>[email protected]</td>
        </tr>
        <!-- Add more rows here -->
    </tbody>
</table>

Step 2: Export HTML Table to CSV

In your view, convert the HTML table to CSV format (You need to install pip install beautifulsoup4):

# views.py

from django.http import HttpResponse
import csv
from bs4 import BeautifulSoup

def export_html_to_csv(request):
    html = """
    <!-- Your HTML table content here -->
    """
    soup = BeautifulSoup(html, 'html.parser')
    data = []

    for row in soup.find_all('tr'):
        cols = row.find_all('td')
        data.append([col.text for col in cols])

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

    writer = csv.writer(response)
    for row in data:
        writer.writerow(row)

    return response

Step 3: Define URL Pattern

Add a URL pattern for this export view in your app’s urls.py:

# myapp/urls.py

urlpatterns = [
    # Other URL patterns
    path('export-html-to-csv/', views.export_html_to_csv, name='export_html_to_csv'),
]

Now, accessing /export-html-to-csv/ will convert the HTML table in your template to a CSV file for download.

Conclusion

Exporting data to CSV files is a common requirement in web applications, and Django makes it relatively simple to accomplish. In this tutorial, we created a Django view to export data to a CSV file, added a URL pattern for the view, and optionally created a template for an export button. Also can easily export data from Django QuerySets or HTML tables to CSV files in your Django applications.You can now integrate this functionality into your Django projects to provide users with downloadable CSV exports for their data needs.

Find this tutorial on Github.

Blogs You Might Like to Read!