Create a Joke Generator in Django

Faraz

By Faraz - July 29, 2024

Learn how to create a simple joke generator in Django with our easy-to-follow guide. Perfect for beginners! Step-by-step instructions and styling tips included.


create-a-joke-generator-in-django.webp

Creating a joke generator in Django is a fun and educational project that can help you get started with web development. This guide will walk you through setting up a basic Django app that randomly displays jokes. Whether you’re a beginner looking to learn Django or just want to create a light-hearted app, this step-by-step tutorial will make it easy to build your own joke generator.

Setting Up Your Django Project

Installing Django

Before starting, ensure you have Python installed. You can install Django using pip:

pip install django

Creating a new Django project

Create a new Django project using the following command:

django-admin startproject joke_generator

Setting up the project structure

Navigate into your project directory:

cd joke_generator

Create a Django App

Create a new app within your project:

python manage.py startapp joke

Adding the app to the project

Add joke to INSTALLED_APPS in joke_generator/settings.py:

INSTALLED_APPS = [
    'joke',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Create a Joke Generator

Create Views

Define a view in joke/views.py to handle joke generation:

from django.shortcuts import render
import random

# List of jokes
JOKES = [
    "Why don't scientists trust atoms? Because they make up everything!",
    "Why did the math book look sad? It had too many problems.",
    "Why don't programmers like nature? It has too many bugs.",
    "What do you get when you cross a snowman and a vampire? Frostbite.",
    "A Pen is worth a thousand docs.",
    "Be the developer your linter thinks you are.",
    "How do you comfort a JavaScript bug? You console it.",
    "How would you React if I said I love Vue.",
    "If a groundhog inspects their Web Component, do they see their Shadow DOM.",
    "If you get tired, be like an AJAX request and REST.",
    "If you want to flex your skills and go off the grid, try coding a layout with float.",
    "Keep friends close and formatters closer.",
    "Keep the <main> thing the <main> thing.",
    "Knock knock! Race condition. Who's there.",
    "Learning 3D transforms in CSS requires a little perspective.",
    "Old programmers never die; they just lose some of their functions.",
    "Promise you'll await for me.",
    "Save your sass for CSS. Everywhere else, be kind.",
    "The best caches are like the best hugs. Warm.",
    "The Pen is mightier than the sword.",
    "There are 10 kinds of people, those who understand binary and those who don't.",
    "There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.",
    "Two CSS properties walk into a bar. A barstool in a completely different bar falls over.",
    "We would have called your functions earlier, but we were in a bind.",
    "We'd ask you for an infinite loop joke, but we'd never hear the end of it.",
    "We're stronger <u>nited than <div>ided.",
    "What did the colon say to the semicolon? Stop winking at me.",
    "What did the HTML say to the CSS? I like your style.",
    "What do you call a two-legged ghost cow? Boolean Beef.",
    "What's a functional programmer's favorite animal? A lamb, duh.",
    "Who's loopier? A fruit loop or a for loop.",
    "Why did the programmer quit her job? She didn't get arrays.",
    "πŸ’• I'm the CSS to your HTML."
]

def joke_generator(request):
    joke = random.choice(JOKES)
    return render(request, 'joke.html', {'joke': joke})

Create a URL Pattern:

In joke, create a new file named urls.py and define the URL pattern:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.joke_generator, name='joke_generator'),
]

And include this URL configuration in joke_generator/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('joke.urls')),
]

Create Templates

Create a template to display the joke. Create a file joke/templates/joke.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Joke Generator</title>
    <style>
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    text-align: center;
    max-width: 600px;
    width: 100%;
}
h1 {
    color: #333;
}
p {
    font-size: 18px;
    color: #555;
}
button {
    background-color: #007bff;
    border: none;
    color: white;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
button:hover {
    background-color: #0056b3;
}
    </style>
</head>
<body>
    <div class="container">
        <h1>Joke Generator</h1>
        <p>{{ joke }}</p>
        <button onclick="window.location.reload();">Get Another Joke</button>
    </div>
</body>
</html>

Run the Django Server

Apply Migrations:

Apply migrations to set up the database (necessary even if not using a database for this app):

python manage.py migrate

Run the Development Server:

Start the Django development server:

python manage.py runserver

Visit Your App:

Now, visit http://127.0.0.1:8000/ in your browser, and you should see the joke generator in action.

Full Project Structure

joke_generator/
β”œβ”€β”€ joke/
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ templates/
β”‚   β”‚       └── joke.html
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ apps.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ tests.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── views.py
β”œβ”€β”€ joke_generator/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ manage.py
└── requirements.txt

Conclusion

With this simple Django joke generator, you’ve learned how to set up a basic web app that serves random jokes. This project not only demonstrates the power of Django but also provides a fun way to practice your coding skills. Feel free to expand this project by adding more features or integrating it with an external joke API.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below πŸ”₯ and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our siteπŸ₯Ί