How to Create CSV File In Django?

Published On: 03/08/2022 | Category: Django

Hi Dev,

Today, django create csv file example is our main topic. I explained simply about django create csv file for download. we will help you to give example of how to create csv file in django. This article will give you simple example of how to generate and download csv file in django. Alright, let’s dive into the steps.

There are several ways to create text file in django. we will use HttpResponse and pass the argument content_type='text/csv'. so let's see the below examples.

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp core
Step 3 : Update

Here, do not forget to register the new app in the file. Under installed apps, just add ‘core’ to the list:

Step 4 : Creating the Views

In this step, we need to create the views for performing ajax image upload to the database.Open the core/ file and add.

from django.shortcuts import render
from django.http import HttpResponse
import csv

def writetofile(request):  
    response = HttpResponse(content_type='text/csv')  
    response['Content-Disposition'] = 'attachment; filename="demo.csv"'  
    writer = csv.writer(response)
    writer.writerow(['ID', 'First Name','Last Name','Age'])
    writer.writerow(['1', 'Bhavesh', 'Sonagra', '25'])  
    writer.writerow(['2', 'Vishal', 'Patel', '22'])  
    return response
Step 5 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the core/ file and update it as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('download-csv/', views.downloadZip, name='download')

Next, we will require the modify the your root preoject folder lets update the file.

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

urlpatterns = [
    path('', include('core.urls'),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the address with a web browser.


I Hope It will help you....