Building a Django Blog from Scratch


Django: Building a Blog from Scratch

Follow these steps to create a complete blog application using Django, Python's most popular web framework.

Step 1: Install Django

pip install django

Step 2: Create Your Django Project

django-admin startproject myblog
cd myblog

Step 3: Create a Blog App

python manage.py startapp blog

Add 'blog' to INSTALLED_APPS in myblog/settings.py:

INSTALLED_APPS = [
    ...
    'blog',
]

Step 4: Define Blog Post Model

In blog/models.py:

from django.db import models

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

    def __str__(self):
        return self.title

Step 5: Apply Migrations

python manage.py makemigrations
python manage.py migrate

Step 6: Register the Model in Admin

In blog/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Create superuser:

python manage.py createsuperuser

Then run the server and login to /admin to add posts:

python manage.py runserver

Step 7: Create Views for the Blog

In blog/views.py:

from django.shortcuts import render
from .models import Post

def home(request):
    posts = Post.objects.all().order_by('-created_at')
    return render(request, 'blog/home.html', {'posts': posts})

Step 8: Set Up URLs

In myblog/urls.py:

from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
]

Step 9: Create Templates

Create the folder blog/templates/blog/ and inside it:

home.html

<!DOCTYPE html>
<html>
<head>
    <title>Django Blog</title>
</head>
<body>
    <h1>My Django Blog</h1>
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
        <p><em>by {{ post.author }} on {{ post.created_at }}</em></p>
        <p>{{ post.content|linebreaks }}</p>
        <hr>
    {% endfor %}
</body>
</html>

Make sure Django knows where to find templates. In myblog/settings.py, add:

'DIRS': [BASE_DIR / 'templates'],

Step 10: Run the App

python manage.py runserver

Visit http://127.0.0.1:8000/ — you'll see your blog posts displayed!

Bonus: Add a Single Post Page

Update views.py:

from django.shortcuts import get_object_or_404

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

Update urls.py:

path('post/<int:post_id>/', views.post_detail, name='post_detail'),

Create detail.html template.

Done!

You now have a functional Django blog with:

  • Admin panel
  • Homepage with blog posts
  • Dynamic templates