Preface

In web development, quickly building a blog system with Python is a common goal for beginners. As a “batteries-included” Python web framework, Django provides core components like ORM (Object-Relational Mapping) and a template engine, significantly simplifying the development process. This article will guide you through creating a blog system that displays article lists from scratch using Django, focusing on understanding Django’s core concepts—ORM for data operations and templates for page rendering.

Step 1: Environment Setup and Project Initialization

To start development, first install Django and set up the project structure.

1. Install Django

Open your terminal (Command Prompt) and run the following command to install the latest Django:

pip install django

Verify the installation:

django-admin --version  # Should output the version, e.g., 3.2.20

2. Create Django Project and App

A Django project is a container for a complete web application, while an app is a functional module.
- Create the project:

  django-admin startproject myblog  # Project name: myblog
  cd myblog  # Navigate into the project directory
  • Create the app:
  python manage.py startapp blog  # App name: blog

Your project structure will look like this (key files):

myblog/
├── myblog/          # Project configuration directory
   ├── __init__.py
   ├── settings.py  # Global settings (e.g., database, app list)
   ├── urls.py      # Project URL routing
   └── wsgi.py
├── blog/            # Blog app directory
   ├── __init__.py
   ├── models.py    # Data model definition (ORM core)
   ├── views.py     # View functions (request handling)
   └── urls.py      # App URL routing
└── manage.py        # Django CLI tool (migrations, server startup, etc.)

Step 2: Define Blog Data Model with ORM

ORM is a core Django feature that lets you define database table structures using Python classes (no raw SQL needed). We’ll define a “Post” model for blog articles.

1. Define the Data Model

In blog/models.py, write a Post class to represent the article table:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)  # Article title (string, max 200 chars)
    content = models.TextField()              # Article content (long text)
    pub_date = models.DateTimeField(auto_now_add=True)  # Publish time (auto-set to current time)

    def __str__(self):
        return self.title  # Display title in the admin interface
  • Explanation:
  • models.Model: Base class for Django models, automatically mapping to database tables.
  • CharField/TextField: Corresponding to database string/long-text fields.
  • DateTimeField(auto_now_add=True): Automatically records creation time without manual input.

2. Activate the Model and Create Database Tables

Django uses SQLite by default (no extra setup needed). Add the app to project settings:
- Open myblog/settings.py and add 'blog' to INSTALLED_APPS:

  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'blog',  # Add our blog app
  ]
  • Create database tables (migrations):
  python manage.py makemigrations  # Generate migration files (model → SQL)
  python manage.py migrate         # Execute migrations to create tables

This creates a blog_post table in the database to store article data.

Step 3: Write Views and Templates to Display Blog Content

Views handle user requests and return data; templates render data into HTML pages.

1. Write View Functions

In blog/views.py, define a view to fetch all articles from the database and pass them to the template:

from django.shortcuts import render
from .models import Post  # Import the Post model

def index(request):
    # Get all posts, ordered by publication date (newest first)
    posts = Post.objects.all().order_by('-pub_date')
    # Render the template with the posts data
    return render(request, 'blog/index.html', {'posts': posts})

2. Configure Routing

Django routes requests via URLs.
- In blog/urls.py, define app-specific routes:

  from django.urls import path
  from . import views

  urlpatterns = [
      path('', views.index, name='index'),  # Root URL maps to index view
  ]
  • Include the app routes in the project’s myblog/urls.py:
  from django.contrib import admin
  from django.urls import include, path

  urlpatterns = [
      path('admin/', admin.site.urls),
      path('', include('blog.urls')),  # Project root routes to blog app
  ]

3. Create Template Files

Templates render data into HTML. Create blog/templates/blog/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>My Blog</title>
    <style>
        body { font-family: Arial; max-width: 800px; margin: 0 auto; padding: 20px; }
        .post { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 5px; }
        h2 { color: #333; }
    </style>
</head>
<body>
    <h1>My First Blog</h1>
    {% if posts %}  <!-- Django template syntax: check if posts exist -->
        {% for post in posts %}  <!-- Loop through all posts -->
            <div class="post">
                <h2>{{ post.title }}</h2>  <!-- Display title -->
                <p>Published on: {{ post.pub_date|date:"Y-m-d H:i" }}</p>  <!-- Format date -->
                <p>{{ post.content }}</p>  <!-- Display content -->
            </div>
        {% endfor %}
    {% else %}
        <p>No posts yet! Publish your first article.</p>
    {% endif %}
</body>
</html>
  • Template Syntax:
  • {{ post.title }}: Outputs the variable (article title).
  • {% for post in posts %}: Loops through the post list.
  • {{ post.pub_date|date:"Y-m-d H:i" }}: Formats the date using a filter.

Run the Blog System and View Results

Start the development server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser to see the blog! To add articles, explore Django’s admin interface (covered later).

Summary

In these 3 steps, we built a simple blog system using Django, focusing on:
1. ORM: Define database tables with Python classes (no SQL required).
2. Template Engine: Dynamically render data with HTML + template syntax.
3. MVT Architecture: Model (data storage) → View (logic) → Template (presentation).

Next, expand features like single article pages, user authentication, or comments to enhance your Django skills!

Xiaoye