How to generate and download a CSV file in Django
In this article, you will learn how to generate and download a CSV file using the Django.
Django is a free, open-source, Python-based framework. It enables fast development of any type of web application. It is secure, maintainable, portable and scalable. The main advantages of using Django are that it has fully loaded common web development tasks, like administration, authentication, site maps, etc.
The CSV file stands for "Comma-separated-values", as it uses a comma to separate values. This is a widely used file format that stores data in a tabular format. All the most popular programming languages have tools or applications to support the CSV file format. In web development, we can easily import/export to a CSV file, and we can also convert any file format to a CSV file. Like other programming languages, we can also generate a CSV file in Django.
These are the step-by-step instructions to generate a CSV file
The Django project first needs to activate the virtualenv to create a new virtual environment for your project.
c:\python37\Scripts\projects>cd env\Scripts
c:\python37\Scripts\projects\env\Scripts>activate
(env) c:\python37\Scripts\projects\env\Scripts>cd..
Here, we have created a new project 'generatecsv' and a new app 'gcsv'.
(env) c:\python37\Scripts\projects>django-admin startproject generatecsv
(env) c:\python37\Scripts\projects>cd generatecsv
(env) c:\python37\Scripts\projects\generatecsv>django-admin startapp gcsv
views.py
Django comes with a csv library. So there is no need to install the library package, we can directly import it in the views file.
import csv
For generating CSV, we will use a HTTPResponse object as it is a file like object and set the response mime type 'text/csv'. This tells the browser that the document is a CSV file rather than a normal HTML file.
HttpResponse('text/csv')
The CSV module has many predefined functions to perform different operations for a csv file. To write in a CSV file, we will use 'csv.writer()' function, and to write on each row in your CSV file, we will use the 'writer.writerow()' function.
Here is the complete code of the 'views.py' file.
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
import csv
# Students name
NAME = ['Riya','Suzzane','George','Zoya','Smith','Henry']
# QUIZ Subject
SUBJECT = ['CHE','PHY','CHE','BIO','ENG','ENG']
def psg(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse('text/csv')
response['Content-Disposition'] = 'attachment; filename=quiz.csv'
# Create the CSV writer using the HttpResponse as the "file"
writer = csv.writer(response)
writer.writerow(['Student Name', 'Quiz Subject'])
for (name, sub) in zip(NAME, SUBJECT):
writer.writerow([name, sub])
return response
Now, open 'urls.py' and put the following code.
from django.contrib import admin
from django.urls import path
from gcsv import views
urlpatterns = [
path('admin/', admin.site.urls),
path('gcsv',views.psg),
]
Here, we are migrating the project.
(env) c:\python37\Scripts\projects\generatecsv>python manage.py migrate
On successful migration, it returns something like this-
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
At last, run the project using the following command.
(env) c:\python37\Scripts\projects\generatecsv>python manage.py runserver
If everything is correct, then it returns something like this-
System check identified no issues (0 silenced).
January 13, 2020 - 20:57:08
Django version 3.0.2, using settings 'generatecsv.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open the 'http://127.0.0.1:8000/' on the browser, it generates and downloads the CSV file.
Related Articles
Django ajax GET and POST requestDjango Pagination with Ajax and jQuery
Display image from database in Django
How to upload image and add in Django model Imagefield
How to read and write a file using Django
Django pass variable from view to HTML template
Get data from MySQL in Django View with Models
Django serialize queryset into JSON and display in template
Django serialize queryset into JSON and display in template
Django Export Model Data to CSV
How to get data from MySQL in Django View with Models
Windows commands to Create and Run first Django app
Django Send Mail on Contact form submission
How to insert data in MySQL database from an HTML form using Django
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python