Django Projects for Beginners: A Step-by-Step Guide

Imagine building dynamic websites with Python, creating interactive experiences for users, and mastering a framework that powers some of the web’s biggest platforms. That’s the power of Django, and it’s more accessible than you might think. This comprehensive guide will walk you through several Django projects perfect for beginners, equipping you with the skills to create your own web applications.

Why Django is Perfect for Beginners

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. But what does that actually mean? It means less reinventing the wheel and more building the features that make your project unique. Here’s why it’s an excellent choice for newcomers:

  • Batteries Included: Django comes with a vast array of built-in features, including an ORM (Object-Relational Mapper), templating engine, form handling, and security features.
  • DRY (Don’t Repeat Yourself): Django emphasizes code reusability, reducing redundancy and making your code easier to maintain.
  • Security: Django takes security seriously, providing built-in protection against common web vulnerabilities like cross-site scripting (XSS) and SQL injection.
  • Large Community and Documentation: Django boasts a thriving community and excellent documentation, ensuring you’ll find help and resources when you need them.
  • Scalability: Django is designed to handle projects of all sizes, from simple personal blogs to complex enterprise applications.

Setting Up Your Django Development Environment

Before diving into projects, let’s set up your development environment. This involves installing Python, pip (Python’s package installer), and Django itself.

  1. Install Python: Download the latest version of Python from the official Python website (python.org) and follow the installation instructions for your operating system. Make sure to add Python to your system’s PATH environment variable.
  2. Install pip: Pip usually comes bundled with Python. Verify it’s installed by opening your terminal or command prompt and typing `pip –version`. If it’s not installed, follow the instructions on the pip website (pip.pypa.io).
  3. Install Django: Use pip to install Django by running the command: `pip install Django`. It’s highly recommended to use a virtual environment to isolate your project dependencies.

Creating a Virtual Environment

A virtual environment creates an isolated space for your project’s dependencies. This prevents conflicts between different projects and keeps your global Python installation clean.

  1. Create a virtual environment: Open your terminal or command prompt, navigate to your project directory, and run the command: `python -m venv venv`. Replace venv with any name you prefer for your environment.
  2. Activate the virtual environment:
    • Windows: `venvScriptsactivate`
    • macOS/Linux: `source venv/bin/activate`

    You’ll know the environment is activated when you see the environment name in parentheses before your command prompt.

Project 1: Simple To-Do List Application

Our first project is a classic: a simple to-do list application. This project will introduce you to Django’s models, views, templates, and forms.

Creating the Project

  1. Create a Django project: In your terminal, navigate to the directory where you want to store your projects and run the command: `django-admin startproject todolist`. Replace todolist with your desired project name.
  2. Navigate to the project directory: `cd todolist`
  3. Create a Django app: Run the command: `python manage.py startapp tasks`. Apps are modular components of your Django project.

Defining the Model

Open the `tasks/models.py` file and define the `Task` model:

python
from django.db import models

class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)

def __str__(self):
return self.title

This model defines two fields: `title` (the task description) and `completed` (a boolean indicating whether the task is done).

Registering the Model

Open `tasks/admin.py` and register the `Task` model:

python
from django.contrib import admin
from .models import Task

admin.site.register(Task)

This will allow you to manage your tasks through Django’s admin interface.

Creating and Running Migrations

Migrations are how Django applies changes to your database schema.

  1. Create migrations: Run the command: `python manage.py makemigrations tasks`
  2. Apply migrations: Run the command: `python manage.py migrate`

Creating Views

Open `tasks/views.py` and define the views for listing, creating, and updating tasks:

python
from django.shortcuts import render, redirect
from .models import Task

def task_list(request):
tasks = Task.objects.all()
return render(request, ‘tasks/task_list.html’, {‘tasks’: tasks})

def create_task(request):
if request.method == ‘POST’:
title = request.POST[‘title’]
Task.objects.create(title=title)
return redirect(‘task_list’)
return render(request, ‘tasks/create_task.html’)

def complete_task(request, task_id):
task = Task.objects.get(pk=task_id)
task.completed = True
task.save()
return redirect(‘task_list’)

These views handle retrieving tasks, creating new tasks, and marking tasks as complete.

Creating Templates

Create a `templates` directory inside the `tasks` directory. Inside `templates`, create a `tasks` directory. This is where you’ll store your HTML templates.

Create three templates: `tasks/task_list.html`, `tasks/create_task.html`.

**tasks/task_list.html:**




To-Do List

To-Do List

    {% for task in tasks %}

  • {{ task.title }}
    {% if task.completed %}
    (Completed)
    {% else %}
    Complete
    {% endif %}
  • {% endfor %}

Add Task

**tasks/create_task.html:**




Create Task

Create Task

{% csrf_token %}



Back to List

Configuring URLs

Create a `tasks/urls.py` file:

python
from django.urls import path
from . import views

urlpatterns = [
path(”, views.task_list, name=’task_list’),
path(‘create/’, views.create_task, name=’create_task’),
path(‘complete//’, views.complete_task, name=’complete_task’),
]

Then, include these URLs in your project’s `urls.py` file (`todolist/urls.py`):

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

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘tasks/’, include(‘tasks.urls’)),
]

Running the Development Server

Run the command: `python manage.py runserver` and visit `http://127.0.0.1:8000/tasks/` in your browser. You should see your to-do list application!

Related image

Project 2: A Simple Blog

Now, let’s build a classic: a simple blog. This project expands on the previous one, introducing you to more complex models, form handling, and template design.

Creating the App

Run the command: `python manage.py startapp blog`

Defining the Post Model

Open `blog/models.py` and define the `Post` model:

python
from django.db import models

class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_published = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

Creating the Admin Interface

Register the `Post` model in `blog/admin.py`:

python
from django.contrib import admin
from .models import Post

admin.site.register(Post)

Creating Views

Open `blog/views.py` and define the views for listing and creating posts:

python
from django.shortcuts import render, redirect
from .models import Post
from django.views.generic import ListView, CreateView
from django.urls import reverse_lazy

class PostListView(ListView):
model = Post
template_name = ‘blog/post_list.html’
context_object_name = ‘posts’

class PostCreateView(CreateView):
model = Post
template_name = ‘blog/post_create.html’
fields = [‘title’, ‘content’]
success_url = reverse_lazy(‘post_list’)

Here, we’re using class-based views, which are a powerful way to organize your views.

Creating Templates

Create the following templates in `blog/templates/blog`: `post_list.html` and `post_create.html`.

**blog/templates/blog/post_list.html:**




Blog

Blog Posts

    {% for post in posts %}

  • {{ post.title }}

    {{ post.content|truncatewords:50 }}

    Published: {{ post.date_published }}

  • {% endfor %}

Create New Post

**blog/templates/blog/post_create.html:**




Create Post

Create New Post

{% csrf_token %}
{{ form.as_p }}

Back to List

Configuring URLs

Create a `blog/urls.py` file:

python
from django.urls import path
from .views import PostListView, PostCreateView

urlpatterns = [
path(”, PostListView.as_view(), name=’post_list’),
path(‘create/’, PostCreateView.as_view(), name=’post_create’),
]

Include these URLs in your project’s `urls.py` file:

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

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘blog/’, include(‘blog.urls’)),
]

Running the Server

Run the development server and visit `http://127.0.0.1:8000/blog/` in your browser.

Project 3: A Simple URL Shortener

This project is slightly more advanced and demonstrates how to work with third-party libraries and custom URL routing.

Creating the App

Run the command: `python manage.py startapp shortener`

Defining the Model

Open `shortener/models.py`:

python
from django.db import models
import random
import string

def generate_short_url():
characters = string.ascii_letters + string.digits
short_url = ”.join(random.choice(characters) for i in range(6))
return short_url

class ShortenedURL(models.Model):
long_url = models.URLField()
short_url = models.CharField(max_length=6, unique=True, blank=True)

def save(self, *args, **kwargs):
if not self.short_url:
self.short_url = generate_short_url()
super().save(*args, **kwargs)

def __str__(self):
return f'{self.long_url} -> {self.short_url}’

Creating Views

Open `shortener/views.py`:

python
from django.shortcuts import render, redirect, get_object_or_404
from .models import ShortenedURL
from django import forms

class URLForm(forms.Form):
long_url = forms.URLField(label=Enter URL)

def shorten_url(request):
if request.method == ‘POST’:
form = URLForm(request.POST)
if form.is_valid():
long_url = form.cleaned_data[‘long_url’]
shortened_url, created = ShortenedURL.objects.get_or_create(long_url=long_url)
return render(request, ‘shortener/result.html’, {‘shortened_url’: shortened_url})
else:
form = URLForm()
return render(request, ‘shortener/index.html’, {‘form’: form})

def redirect_original(request, short_url):
url = get_object_or_404(ShortenedURL, short_url=short_url)
return redirect(url.long_url)

Creating Templates

Create the following templates in `shortener/templates/shortener`: `index.html` and `result.html`.

**shortener/templates/shortener/index.html:**




URL Shortener

URL Shortener

{% csrf_token %}
{{ form.as_p }}


**shortener/templates/shortener/result.html:**




Shortened URL

Shortened URL

Shortened URL: {{ request.scheme }}://{{ request.META.HTTP_HOST }}/{{ shortened_url.short_url }}

Shorten Another URL

Configuring URLs

Create a `shortener/urls.py` file:

python
from django.urls import path
from . import views

urlpatterns = [
path(”, views.shorten_url, name=’shortener’),
path(‘/’, views.redirect_original, name=’redirect_original’),
]

Include these URLs in your project’s `urls.py` file:

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

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(”, include(‘shortener.urls’)),
]

Making the base URL dynamic

The previous example assumes that the shortened URLs will be accessed from the root directory (/). To make it accessible from a subdirectory, such as /shortener/, some adjustments are necessary to the root `urls.py` and the `result.html` template.

**1. Update root urls.py**

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

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘shortener/’, include(‘shortener.urls’)),
]

**2. Update templates/shortener/result.html**




Shortened URL

Shortened URL

Shortened URL: {{ request.scheme }}://{{ request.META.HTTP_HOST }}/shortener/{{ shortened_url.short_url }}

Shorten Another URL

Running the Server

Run the development server. Navigate to `http://127.0.0.1:8000/shortener/` to access your app. Open Django’s admin interface and populate with URLs for testing.

Key Django Concepts to Master

As you work through these projects, pay close attention to these key concepts:

  • Models: Define the structure of your data using Django’s ORM.
  • Views: Handle user requests and generate responses, often using templates.
  • Templates: Create dynamic HTML pages that display your data.
  • Forms: Handle user input and data validation.
  • URLs: Map URLs to specific views.
  • Admin Interface: Manage your data through Django’s automatically generated admin interface.

Further Exploration

These projects are just the beginning. Here are some ideas for expanding your Django skills:

  • Add user authentication: Allow users to create accounts, log in, and manage their own data.
  • Implement more complex relationships between models: Explore one-to-many, many-to-many, and other relationship types.
  • Use Django REST Framework: Build powerful APIs using Django.
  • Deploy your projects: Learn how to deploy your Django applications to platforms like Heroku or PythonAnywhere.

Embarking on these beginner-friendly Django projects will not only solidify your grasp of Python web development but also unlock a world of possibilities for creating dynamic and engaging web applications. Happy coding!