Building a Simple Blog with Django
Learn how to create a basic blog using Django, a high-level Python web framework.
Introduction to Django Blog
Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. In this tutorial, we will create a simple blog using Django.
Step 1: Install Django and Create a New Project
To start, you need to have Python and pip installed on your system. Then, install Django using pip:
pip install django
Create a new Django project using the following command:
django-admin startproject blog
Step 2: Create a New App
Navigate into the project directory and create a new app called posts:
python manage.py startapp posts
Step 3: Define the Post Model
In the posts app, define a Post model in models.py:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Step 4: Create and Apply Migrations
Create migrations for the Post model and apply them to the database:
python manage.py makemigrations
python manage.py migrate
Step 5: Create Views and Templates
Create a view to display all posts and a template to render the posts:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'posts/post_list.html', {'posts': posts})
Create a post_list.html template in the posts app's templates directory:
{% extends 'base.html' %}
{% block content %}
<h1>Post List</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }} ({{ post.created_at }})</li>
{% endfor %}
</ul>
{% endblock %}
Step 6: Add URL Patterns
Add URL patterns to map to the post_list view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]