A Python project – A Django blog application

Lesson 13 of 15 · Python projects
Who this project is for:
an advanced project for students who have finished the basic course and the Python for the web lessons – usually secondary school. For grades 5–8, projects with graphics and the micro:bit are a better choice.

In this project we will make a simple blog web application using the Django framework.

A blog application shows a list of articles and lets you read individual posts.

In this project you will learn:
  • how to make a Django project
  • how to define models
  • how to show data in a template
  • how to make a basic blog system

Project structure


blog_project/

manage.py

blog/

models.py
views.py
urls.py

templates/

blog/
    index.html

A Django model for a blog post


from django.db import models

class Post(models.Model):

    title = models.CharField(max_length=200)

    text = models.TextField()

    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

The view function


from django.shortcuts import render
from .models import Post

def index(request):

    posts = Post.objects.all()

    return render(request,"blog/index.html",
                  {"posts":posts})

The HTML template


<html>

<head>
<title>My Django blog</title>
</head>

<body>

<h1>Blog posts</h1>

{% for p in posts %}

<h2>{{ p.title }}</h2>

<p>{{ p.text }}</p>

<hr>

{% endfor %}

</body>

</html>

How this application works

  • the Django model defines the structure of the data
  • the posts are stored in a database
  • the view function loads the posts
  • the template shows the content in the browser
The Django admin panel makes it easy to add and edit blog posts.

Possible improvements to the project

  • add a page for a single post
  • add comments
  • add categories
  • add a user system

Related lessons


The end of the Python projects section

With this project we finish the basic collection of Python projects. Two more advanced projects follow: an advanced REST API and a chat server. After these projects you can continue with more advanced web applications, data analysis or game development.

How to make the project your own:
1) first run the given code without changes, 2) change one thing and predict what will happen, 3) add at least one feature of your own, 4) write down in a notebook what you changed and why. A work log like that is the basis of a creative programming paper.