7 b] Describe how to generate non-HTML content like CSV and PDF using Django.
Generating CSV Files
CSV files are simple text files with comma-separated values. Django provides an easy way to generate these files using Python’s csv
module.
1. Create a View for CSV Generation
In your Django app, create a view that generates and returns a CSV file:
# myapp/views.py import csv from django.http import HttpResponse from .models import YourModel def export_to_csv(request): # Create an HTTP response with CSV content response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="data.csv"' # Create a CSV writer object writer = csv.writer(response) # Write the header writer.writerow(['Column 1', 'Column 2', 'Column 3']) # Fetch data from your model data = YourModel.objects.all() # Write data rows for item in data: writer.writerow([item.field1, item.field2, item.field3]) return response
2. Add a URL Pattern
Add a URL pattern for this view in myapp/urls.py
:
# myapp/urls.py from django.urls import path from .views import export_to_csv urlpatterns = [ path('export-csv/', export_to_csv, name='export_to_csv'), ]
Generating PDF Files with ReportLab Canvas
For generating PDF files, you can use the canvas
module from the reportlab
library, which allows you to draw text and shapes directly onto a PDF document.
1. Install ReportLab
First, install the reportlab
library if you haven’t already:
pip install reportlab
2. Create a View for PDF Generation
In your Django app, create a view that generates a PDF using reportlab
’s canvas
:
# myapp/views.py from io import BytesIO from django.http import HttpResponse from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from .models import YourModel def export_to_pdf(request): # Create an in-memory buffer to receive the PDF data buffer = BytesIO() # Create a PDF canvas object p = canvas.Canvas(buffer, pagesize=letter) # Define some styles p.setTitle("PDF Report") # Write some text p.drawString(100, 750, "PDF Report") # Add a table or data from the model data = YourModel.objects.all() y = 730 for item in data: p.drawString(100, y, f"{item.field1} - {item.field2} - {item.field3}") y -= 20 # Finish up p.showPage() p.save() # Get PDF data from the buffer pdf = buffer.getvalue() buffer.close() # Create an HTTP response with PDF content response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' return response
3. Add a URL Pattern
Add a URL pattern for this view in myapp/urls.py
:
# myapp/urls.py from django.urls import path from .views import export_to_pdf urlpatterns = [ path('export-pdf/', export_to_pdf, name='export_to_pdf'), ]