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/models.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.
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
Create the Book Form
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.
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 ('gfg/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.
import csv
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .models import Book
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, 'gfg/create_user_profile.html', {'form': form})
# gfg/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
Configure URLs
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.
# gfg/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"
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('gfg.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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generate CSV</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:

CSV output:
