How to Build a Blog from Scratch with Django: A Step-by-Step Guide

Django makes building a blog remarkably efficient. This tutorial will guide you through creating a fully functional blog from scratch, covering models, views, templates, and URLs. You’ll have a working blog ready to deploy in minutes.

First, ensure Python and pip are installed. Create a virtual environment, install Django, and start a new project: django-admin startproject myblog. Then create a blog app: python manage.py startapp blog. Add 'blog' to INSTALLED_APPS in settings.py.

Article illustration

1. Define Your Blog Model

Open blog/models.py and create a Post model with fields for title, slug, content, and publication date.

from django.db import models
from django.utils import timezone

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    content = models.TextField()
    published_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

Run python manage.py makemigrations then migrate to create the database table.

2. Create Views and Templates

In blog/views.py, add a view to list all posts and another to show a single post detail.

List View

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

Detail View

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    return render(request, 'blog/post_detail.html', {'post': post})

Create a blog/templates/blog/ folder and add post_list.html and post_detail.html with simple loops and variable output.

3. Configure URLs

In blog/urls.py, map the views:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('<slug:slug>/', views.post_detail, name='post_detail'),
]

Include the blog URLs in the project’s urls.py:

from django.urls import include, path

urlpatterns = [
    path('', include('blog.urls')),
]

4. Run and Test Your Blog

Run python manage.py runserver and visit http://127.0.0.1:8000/. You should see your blog. Use the Django admin to add posts (register Post in admin.py first).

Congratulations! You’ve built a Django blog from scratch. Expand it with categories, comments, or markdown support as you grow.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *