0% found this document useful (0 votes)
19 views

Experiment-11 Full Stack Django Search Creators

Fsd experiment 11

Uploaded by

Madhushree C K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Experiment-11 Full Stack Django Search Creators

Fsd experiment 11

Uploaded by

Madhushree C K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

| Full Stack Django Development|

Experiment-11

Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.

Step-01: This app will be created in the Django project we made earlier.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., fullstack_project/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Search Creators…. Page 106


| Full Stack Django Development|

Step-03: Create models

• Open the models.py file inside the student_course_registration_app and define your
models:

from django.db import models

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.CharField(max_length=200)

publication_date = models.DateField()

def __str__(self):

return self.title

Search Creators…. Page 107


| Full Stack Django Development|

Step-04: Create a views.py file in your books app and define the views for generating CSV
and PDF files

import csv

from django.http import HttpResponse

from django.template.loader import get_template

from xhtml2pdf import pisa

from .models import Book

def export_books_csv(request):

response = HttpResponse(content_type='text/csv')

response['Content-Disposition'] = 'attachment; filename="books.csv"'

writer = csv.writer(response)

writer.writerow(['Title', 'Author', 'Publication Date'])

books = Book.objects.all().values_list('title', 'author', 'publication_date')

for book in books:

writer.writerow(book)

return response

def export_books_pdf(request):

books = Book.objects.all()

template_path = 'book_list.html'

context = {'books': books}

Search Creators…. Page 108


| Full Stack Django Development|

response = HttpResponse(content_type='application/pdf')

response['Content-Disposition'] = 'attachment; filename="books.pdf"'

template = get_template(template_path)

html = template.render(context)

pisa_status = pisa.CreatePDF(

html, dest=response)

if pisa_status.err:

return HttpResponse('We had some errors <pre>' + html + '</pre>')

return response

Search Creators…. Page 109


| Full Stack Django Development|

Step-04: In your books app, create a templates directory and an html file for rendering the
PDF:

books/

templates/

books/

book_list.html

book_list.html

<!DOCTYPE html>

<html>

<head>

<title>Book List</title>

<style>

body {

font-family: Arial, sans-serif;

table {

border-collapse: collapse;

width: 100%;

th, td {

padding: 8px;

Search Creators…. Page 110


| Full Stack Django Development|

text-align: left;

border-bottom: 1px solid #ddd;

</style>

</head>

<body>

<h1>Book List</h1>

<table>

<thead>

<tr>

<th>Title</th>

<th>Author</th>

<th>Publication Date</th>

</tr>

</thead>

<tbody>

{% for book in books %}

<tr>

<td>{{ book.title }}</td>

<td>{{ book.author }}</td>

<td>{{ book.publication_date }}</td>

Search Creators…. Page 111


| Full Stack Django Development|

</tr>

{% endfor %}

</tbody>

</table>

</body>

</html>

Search Creators…. Page 112


| Full Stack Django Development|

Step-05: add the URL patterns and import Necessary Packages:

from django.urls import path

from books.views import export_books_csv, export_books_pdf

urlpatterns = [

path('books/export/csv/', export_books_csv, name='export_books_csv'),

path('books/export/pdf/', export_books_pdf, name='export_books_pdf'),

Step-06: Install the xhtml2pdf library for generating PDF files:

pip install xhtml2pdf

Search Creators…. Page 113


| Full Stack Django Development|

Step-07: Create the book titles and author and publication date

Django Shell

• If you just want to create some sample data for testing or development purposes, you can
run the code in the Django shell as shown in the previous example. This is a quick and
easy way to create objects interactively.

Data Migration

• If you want to include the book data as part of your project's initial data setup, you can
create a data migration. Here's how you can do it

Run the following command to create a new data migration

python manage.py makemigrations books –empty

• This will create a new empty migration file in the books/migrations/ directory.
• Open the newly created migration file (e.g., books/migrations/0002_auto_<...>.py) and
add the code to create the book objects in the operations list of the Migration class.

Search Creators…. Page 114


| Full Stack Django Development|

from django.db import migrations

def create_book_data(apps, schema_editor):

Book = apps.get_model('books', 'Book')

Book.objects.bulk_create([

Book(title='To Kill a Mockingbird', author='Harper Lee', publication_date='1960-07-11'),

Book(title='1984', author='George Orwell', publication_date='1949-06-08'),

Book(title='Pride and Prejudice', author='Jane Austen', publication_date='1813-01-28'),

Book(title='The Great Gatsby', author='F. Scott Fitzgerald', publication_date='1925-04-10'),

Book(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-16'),

])

class Migration(migrations.Migration):

dependencies = [

('books', '0001_initial'),

operations = [

migrations.RunPython(create_book_data),

Run the following command to apply the data migration

python manage.py migrate

• This will create the book objects in your database.

Search Creators…. Page 115


| Full Stack Django Development|

Step-08: Custom Script

• If you need to create the book data programmatically (e.g., during deployment or as part
of a data import process), you can create a custom Python script and run it as needed.
• Create a new Python file (e.g., create_book_data.py) in your project's root directory, and
add the code to create the book objects:

import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fullstack_project.settings')

import django

django.setup()

from books.models import Book

Book.objects.bulk_create([

Book(title='To Kill a Mockingbird', author='Harper Lee', publication_date='1960-07-11'),

Book(title='1984', author='George Orwell', publication_date='1949-06-08'),

Book(title='Pride and Prejudice', author='Jane Austen', publication_date='1813-01-28'),

Book(title='The Great Gatsby', author='F. Scott Fitzgerald', publication_date='1925-04-


10'),

Book(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-


16'),

])

Search Creators…. Page 116


| Full Stack Django Development|

Run the script using the following command:

python create_book_data.py

Step-09: Update project URLs

• Open the urls.py file inside your project and include the URLs from the book app:

Search Creators…. Page 117


| Full Stack Django Development|

Step-09: Run the development server

• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server

python manage.py runserver

• Open your web browser and visit http://127.0.0.1:8000/.

• Type or copy this http://127.0.0.1:8000/books/export/csv/

Final Output By Clicking Register Project and Register Student

Fig: CSV File Download Screen

Search Creators…. Page 118


| Full Stack Django Development|

• Type or copy this http://127.0.0.1:8000/books/export/pdf/

Fig: PDF File Download Screen

Search Creators…. Page 119

You might also like