In this tutorial, we’ll walk through building a random quote generator using Django. We’ll integrate the ZenQuotes API for fetching quotes, use Tailwind CSS for responsive styling, and deploy the project on Heroku using Gunicorn. This guide will also include saving quotes in a PostgreSQL database for persistence and future analysis.
📺 For a video tutorial: Check out my YouTube video with a step-by-step walkthrough of this project.
📝 For more Django tutorials: Visit my blog .
Prerequisites
Before you start, ensure you have a basic understanding of Django, Python, and web development. You’ll also need the following tools installed:
Python: Version 3.7+
Django: Version 3.0+
Heroku CLI: For deployment
Git: For version control
Project Overview
We’ll set up a Django project called quote with an app named home. The main functionality will be to fetch a random quote from the ZenQuotes API and display it on a page styled with Tailwind CSS.
Step 1: Set Up Your Django Project and App
Create a New Django Project
django-admin startproject quote
cd quote
python manage.py startapp home
Add the home app to the INSTALLED_APPS in your settings.py:
# quote/settings.py
INSTALLED_APPS = [
...
'home',
]
Configure the Quotes Model
Define a model to store quotes in home/models.py:
# home/models.py
from django.db import models
class Quotes(models.Model):
quote_text = models.TextField()
author_name = models.CharField(max_length=255)
image_url = models.URLField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.author_name}"
class Meta:
verbose_name_plural = 'Quotes'
Run migrations to set up the database:
python manage.py makemigrations
python manage.py migrate
Here's an enhanced and detailed version of your blog post for creating a random quote generator with Django, ZenQuotes API, Tailwind CSS, and deployment to Heroku:
How to Create a Random Quote Generator Using Django, ZenQuotes API, Tailwind CSS, and Deploy on Heroku
In this tutorial, we’ll walk through building a random quote generator using Django. We’ll integrate the ZenQuotes API for fetching quotes, use Tailwind CSS for responsive styling, and deploy the project on Heroku using Gunicorn. This guide will also include saving quotes in a PostgreSQL database for persistence and future analysis.
📺 For a video tutorial: Check out my YouTube video with a step-by-step walkthrough of this project.
📝 For more Django tutorials: Visit my blog here.
Prerequisites
Before you start, ensure you have a basic understanding of Django, Python, and web development. You’ll also need the following tools installed:
Python: Version 3.7+
Django: Version 3.0+
Heroku CLI: For deployment
Git: For version control
Project Overview
We’ll set up a Django project called quote with an app named home. The main functionality will be to fetch a random quote from the ZenQuotes API and display it on a page styled with Tailwind CSS.
Step 1: Set Up Your Django Project and App
Create a New Django Project
bash
Copy code
django-admin startproject quote
cd quote
python manage.py startapp home
Add the home app to the INSTALLED_APPS in your settings.py:
python
Copy code
quote/settings.py
INSTALLED_APPS = [
...
'home',
]
Configure the Quotes Model
Define a model to store quotes in home/models.py:
python
Copy code
home/models.py
from django.db import models
class Quotes(models.Model):
quote_text = models.TextField()
author_name = models.CharField(max_length=255)
image_url = models.URLField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.author_name}"
class Meta:
verbose_name_plural = 'Quotes'
Run migrations to set up the database:
bash
Copy code
python manage.py makemigrations
python manage.py migrate
Step 2: Fetch a Random Quote from ZenQuotes API
ZenQuotes offers a free API for random quotes. We’ll create a view to fetch a quote from ZenQuotes and an image from Picsum, then save and display the data.
Create the View
In home/views.py, create a function to fetch a random quote and image:
# home/views.py
import requests
from django.shortcuts import render
from .models import Quotes
def random_quotes(request):
quote_api_url = 'https://zenquotes.io/api/random'
picsum_api_url = 'https://picsum.photos/800/600'
quote_response = requests.get(quote_api_url)
picsum_response = requests.get(picsum_api_url)
quote = "No quote available"
author = "Unknown"
image_url = None
if quote_response.status_code == 200 and picsum_response.status_code == 200:
quote_data = quote_response.json()
image_url = picsum_response.url
if isinstance(quote_data, list) and len(quote_data) > 0:
quote = quote_data[0].get('q', "No quote available")
author = quote_data[0].get('a', "Unknown")
Quotes.objects.create(quote_text=quote, author_name=author, image_url=image_url)
context = {
'quote': quote,
'author': author,
'image_url': image_url,
}
return render(request, 'random_quotes.html', context)
Configure URLs
Link the view in the urls.py of the home app:
# home/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.random_quotes, name='random_quotes'),
]
Include the home app’s URLs in the main quote/urls.py file:
quote/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
]
Step 3: Create the HTML Template with Tailwind CSS
In the home/templates directory, create random_quotes.html for displaying the random quote:
html
Copy code
<!-- home/templates/random_quotes.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Quote</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.0.1/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-200 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded-lg shadow-lg w-full max-w-md text-center">
<p class="text-gray-800 text-lg font-semibold mb-2">"{{ quote }}"</p>
<p class="text-gray-600 text-sm mb-4">— {{ author }}</p>
<img src="{{ image_url }}" alt="Random Image" class="w-full rounded mt-4">
</div>
</body>
</html>
Step 4: Deploy to Heroku with Gunicorn
Install Gunicorn and Update requirements.txt
Pip install gunicorn django-heroku
pip freeze > requirements.txt
Configure the Procfile for Heroku
Create a Procfile at the project root to define the web process:
text
web: gunicorn quote.wsgi --log-file -
Set Up Heroku Settings in settings.py
Add Heroku settings:
quote/settings.py
Deploy to Heroku
Initialize Git, commit your code, and log in to Heroku:
git init
git add .
git commit -m "Initial commit"
heroku login
Create a new Heroku app and push your code:
heroku create
git push heroku main
Finally, open your app:
heroku open
Conclusion
Congratulations! You've built and deployed a Django-powered random quote generator that fetches quotes from the ZenQuotes API, displays them with a Tailwind-styled interface, and saves them in the database.
📺 For a visual guide: Watch my YouTube video for step-by-step instructions.
📝 For more tutorials like this: Check out my blog .
Let me know in the comments if you have any questions or suggestions! Happy coding!
Top comments (0)