We will learn how to build a simple Django app that lets users add book details and download the data as a CSV file. We'll create models, forms, views and templates, then implement CSV generation to enable easy data export from your web application.
Create Django Project and App
Prerequisites:
Open your terminal and run:
django-admin startproject csv_downloader
cd csv_downloader
python manage.py startapp gfg
Register the App
In csv_downloader/settings.py, add 'gfg' to INSTALLED_APPS:

Define the Book Model
gfg/model.py: This code defines a Django model named Book with three fields: title (for the book title), author (for the author's name) and publication_year (for the publication year of the book). It also includes a __str__ method to display the book's title as its string representation.
Python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_year = models.PositiveIntegerField()
def __str__(self):
return self.title
gfg/forms.py: The provided code defines a Django form called BookForm using the forms.ModelForm class. It's designed to work with the Book model in a Django application. The form includes fields for 'title', 'author' and 'publication_year', which are derived from the corresponding model fields.
Python
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'publication_year']
Create Views
gfg/view.py: The "home" view handles HTTP requests, checking for POST submissions. If valid, it saves book data to the database and redirects to the home page. For GET requests, it displays an empty book input form via an HTML template ('myapp/create_user_profile.html') with the form as context data.
The generate_csv view generates a CSV file as an HTTP response, sets the content type to 'text/csv' with the filename "book_catalog.csv," writes column names as the header, fetches all books from the database, writes book details to the CSV and serves the file for user download upon accessing the view.
Python
from django.http import FileResponse
from reportlab.pdfgen import canvas
from .models import Book
from django.shortcuts import redirect, render
from .forms import BookForm
def home(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect('home') # Redirect to PDF generation after adding a book
else:
form = BookForm()
return render(request, 'myapp/create_user_profile.html', {'form': form})
# csvapp/views.py
import csv
from django.http import HttpResponse
from .models import Book
def generate_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="book_catalog.csv"'
writer = csv.writer(response)
writer.writerow(['Title', 'Author', 'Publication Year'])
books = Book.objects.all()
for book in books:
writer.writerow([book.title, book.author, book.publication_year])
return response
gfg/urls.py: This is the URL file inside the test app .The first path is used to direct to the home page and the second is used to generate the CSV file.
Python
# pdfapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('generate-csv/', views.generate_csv, name='generate_csv'),
]
urls.py: This is the main url file. Here we have included the app URLs by the help of "include"
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mini.urls')),
]
Create the Template
Create directory structure:
gfg/
└── templates/
└── gfg/
└── create_user_profile.html
create_user_profile.html:This file is used to Collect the book information from the user and download the csv file after collecting all the data from the user.
Python
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generate PDF</title>
</head>
<body>
<h1>Generate and Download CSV</h1>
<h2>Add a New Book</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Book</button>
</form>
<!-- <p><a href="{% url 'home' %}" download>Download Book Catalog (PDF)</a></p> -->
<p><a href="{% url 'generate_csv' %}" download>Download Book Catalog (CSV)</a></p>
<br>
</body>
</html>
Apply Migrations
Run migrations to create the database tables:
python manage.py makemigrations
python manage.py migrate
Run the Development Server
Start your Django server:
python manage.py runserver
Output:
Generate and Download CSV
CSV Output
Similar Reads
How to create CSV output in Flask? In this article, we will see how to create a CSV output using Flask. Python and Flask Web Frameworks provide powerful tools to generate a report, export data and create catalogs. We will see how to generate both CSV files using Python and Flask. Creating CSV files in Python FlaskStep 1: Installation
3 min read
Python - Import CSV into PostgreSQL In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example
2 min read
Pandas Read CSV in Python CSV files are the Comma Separated Files. It allows users to load tabular data into a DataFrame, which is a powerful structure for data manipulation and analysis. To access data from the CSV file, we require a function read_csv() from Pandas that retrieves data in the form of the data frame. Hereâs a
6 min read
How to Export DataFrame to CSV in R ? R Programming language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to Export DataFrame to CSV file in R Programming Language. Approach:Â Write Data in column wise formatCreate DataFrame for these dataWrite Data to the CS
1 min read
Export Pandas dataframe to a CSV file When working on a Data Science project one of the key tasks is data management which includes data collection, cleaning and storage. Once our data is cleaned and processed itâs essential to save it in a structured format for further analysis or sharing.A CSV (Comma-Separated Values) file is a widely
2 min read