Django export CSV – You’ll learn to write a django based web application and write the data to a CSV file. I will explain to you how to Create CSV (Comma Separated Value) file with Django. We are going to use Python in-built CSV library which comes by default with Python. With this tutorial, you will be able to read write a CSV file and download it with Django. Source Code is also available on GitHub. Learn to django create csv from database.

Django CSV Examples - How to Create CSV File With Django

Following you will be learning in this tutorial:

  • Write Operation
    • Simple CSV Write/Export Operation
    • Writing/Export CSV File From a Dictionary
    • Database Data Dynamic CSV Write/Export Operation
  • Read Operation
    • Simple CSV Read Operation

Quick Django Application Setup

Type the bellow commands in terminal

mkdir django_csv
cd django_csv
virtualenv env
pip3 install django
django-admin startproject django_csv .
django-admin startapp csv_app

Open your settings.py file and add app name, which we have created with the name csv_app

INSTALLED_APPS = [
    ...,

    'csv_app', # <- this
]

Create a View to display all html code

from django.views.generic.base import TemplateView

class CSVPageView(TemplateView):
    template_name = "csv_home.html"

csv_app/templates/csv_home.html

<!DOCTYPE html>
<html>
    <head><title>CSV Examples</title></head>
    <body>
        <h3>CSV Example - Read Write Examples</h3>
        <ul>
            <li>Write Operation
                <ul>
                    <li>
                        <a href="{% url 'csv_simple_write' %}">Simple CSV Write Operation</a>
                    </li>
                    <li>
                        <a href="{% url 'csv_dictionary_write' %}">Writing CSV File From a Dictionary</a>
                    </li>
                    <li>
                        <a href="{% url 'csv_database_write' %}">Database Data CSV Write Operation</a>
                    </li>
                </ul>
            </li>
            <br>
            <li>Read Operation
                <ul>
                    <li>
                        <a href="{% url 'csv_simple_read' %}">Simple CSV Read Operation</a>
                    </li>
                </ul>
            </li>
        </ul>
        {{csv_data}}
        {% if csv_data %}
        sad
            {{csv_data}}
        {% endif %}
    </body>
</html>

Note: if you run the above file it will give an error because we have not created URLs. We are going to create those URLs below in Read/Write operation code.

Create a file named urls.py in your csv_app folder and the code. Note the URLs of these apps can be created here.

from django.urls import path
from csv_app import views

urlpatterns = [
  path('', views.CSVPageView.as_view(), name='csv_home_page'),
]

The last thing, we need to import csv_app/urls.py in the main folder django_csv/urls.py. Edit django_csv/urls.py and django_csv/urls.py should look like below:

from django.contrib import admin
from django.urls import path, include

from csv_app import urls as csv_app_urls

urlpatterns = [
    path('admin/', admin.site.urls),

    path('', include(csv_app_urls))
]

Before getting started, learn some code explanation of Python CSV Library

Python CSV Library Code Explanation

  • HttpResponse(content_type='text/csv') – This tells browsers that the document is a CSV file, instead of HTML file.
  • response['Content-Disposition'] = 'attachment; filename="csv_simple_write.csv"' – This contains CSV filename and downloads files with that name.
  • Hooking into the CSV-generation API is easy: simply pass response because of the initial argument to csv.writer. The csv.writer perform expects a file-like object, and HttpResponse objects match the bill.
  • writer.writerow(['first_name', 'last_name', 'phone_number', 'country']) – Will add/write a row in your csv file.

Simple CSV Export/Write Operation

# csv_app/views.py

import csv
from django.http import HttpResponse

# Simple CSV Write Operation
def csv_simple_write(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="csv_simple_write.csv"'

    writer = csv.writer(response)
    writer.writerow(['first_name', 'last_name', 'phone_number', 'country'])
    writer.writerow(['Huzaif', 'Sayyed', '+919954465169', 'India'])
    writer.writerow(['Adil', 'Shaikh', '+91545454169', 'India'])
    writer.writerow(['Ahtesham', 'Shah', '+917554554169', 'India'])

    return response
# csv_app/urls.py
...
urlpatterns = [
    ...,
    path('export/csv-simple-write/', views.csv_simple_write, name='csv_simple_write'),
]

The above code will download a CSV file with name csv_simple_write.csv with data inside it.

Writing CSV File From a Dictionary

# csv_app/views.py

import csv
from django.http import HttpResponse
# Writing CSV File From a Dictionary 
def csv_dictionary_write(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="csv_dictionary_write.csv"'

    fieldnames = ['first_name', 'last_name', 'phone_number', 'country']
    writer = csv.DictWriter(response, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name':'Huzaif', 'last_name':'Sayyed', 'phone_number':'+919954465169', 'country':'India'})
    writer.writerow({'first_name':'Adil', 'last_name':'Shaikh', 'phone_number':'+91545454169', 'country':'India'})
    writer.writerow({'first_name':'Ahtesham', 'last_name':'Shah', 'phone_number':'+917554554169', 'country':'India'})

    return response
# csv_app/urls.py
...
urlpatterns = [
    ...,
    path('export/csv-dictionary-write/', views.csv_dictionary_write, name='csv_dictionary_write'),
]

The above code will create a CSV file with data from the dictionary.

Dynamic Database Data Export to CSV for Django Export CSV

# csv_app/views.py

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

def csv_database_write(request):

    # Get all data from UserDetail Databse Table
    users = UserDetail.objects.all()

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="csv_database_write.csv"'

    writer = csv.writer(response)
    writer.writerow(['first_name', 'last_name', 'phone_number', 'country'])

    for user in users:
        writer.writerow([user.first_name, user.last_name, user.phone_number, user.country])

    return response
# csv_app/urls.py
...
urlpatterns = [
    ...,
    path('export/csv-database-write/', views.csv_database_write, name='csv_database_write'),
]

The above code will create a CSV file with data from the database. The data will be of the User model.

Simple CSV Read Operation

# csv_app/views.py

import csv
from django.http import HttpResponse
from .models import UserDetail
import os

def csv_simple_read(request):

    path = os.path.dirname(__file__)
    file = os.path.join(path, 'csv_readfile.csv')

    with open(file) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        # See your console/terminal
        for row in csv_reader:
            if line_count == 0:
                print('\n\nColumn names are {}, {}, {}'.format(row[0], row[1], row[3], row[2]))
                line_count += 1
            else:
                print('\t{} {} lives in {}, and his phone number is {}.'.format(row[0], row[1], row[3], row[2]))
                line_count += 1
        print('Processed {} lines.\n\n'.format(line_count))

        return redirect('/') # Redirect to home
# csv_app/urls.py
...
urlpatterns = [
    ...,
    path('export/csv-simple-read/', views.csv_simple_read, name='csv_simple_read'),
]

The above code will read a CSV file and display it in Console and then redirect to the home page.

This tutorial – Write a django based web server to parse a user request (post), and write it to a csv file. Write a django based web server to parse a user request (post) and write it to a csv file.

It is also available on GitHub – https://github.com/studygyaan/How-to-Create-CSV-File-With-Django