আগামী ৩০ সেপ্টেম্বর থেকে Professional web Design and Development with HTML, CSS, JAVASCRIPT, PHP, MySQL, JQUERY and AJAX কোর্স এর ৯৪ তম ব্যাচ এবং ২৭ সেপ্টেম্বর থেকে Zend (PHP 7.1) Certified PHP Engineering (ZCPE) কোর্স এর ৪৪ তম ব্যাচ শুরু হতে যাচ্ছে। সীমিত সংখ্যক আসন বাকি আছে। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

Blog with Django

In this tutorial we will create a blog with Django. This blog will not be very fancy in design. Our main concern will be learning Django framework and its different features.


Let’s create a new folder called “django” anywhere you want. And go to that folder with your console. Run the following command. Don’t forget give the dot(.).

$ django-admin startproject mysite .

Let’s do some recap –

manage.py: is a script that helps with management of the site. With it we will be able to start a web server on our computer without installing anything else, amongst other things.

settings.py: file contains the configuration of your website.

urls.py: file contains a list of patterns used by urlresolver.

Now open settings.py with your IDE. Add the STATIC_ROOT just after the STATIC_URL.

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

The following lines contain the database configuration. We are using sqlite3 for our database. db.sqlite3 is our first database and the location will be our project directory.

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

Now run the following migrate command to create our database –

$ python manage.py migrate

Django models
A model in Django is a special kind of object – it is saved in the database. A database is a collection of data. This is a place in which you will store information about users, your blog posts, etc. We are using a SQLite database to store our data. Django supports ORM. So, it doesn’t matter what database you are using. Just need to change the connection adapter of the database setting to use another DBMS like, MySQL, PostgreSQL etc.

For our blog posts we need some text content. So, we can design our blog model as –


The fields are self-explanatory. Title contains title, text is the text, author is the writer and the created as well as published dates.

Now run the following command from the console –

$ python manage.py startapp blog

The directory structure will be as –

1 django_setup

After creating an application we also need to tell Django that it should use it. So, open mysite/settings.py. We need to find INSTALLED_APPS and add a line containing ‘blog’.


In the blog/models.py file we define all objects called Models. Let’s open blog/models.py, remove everything from it and write code like this:

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

# Create your models here.
class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()

    def __str__(self):
        return self.title

models.CharField – this is how you define text with a limited number of characters.
models.TextField – this is for long text without a limit. Sounds ideal for blog post content, right?
models.DateTimeField – this is a date and time.
models.ForeignKey – this is a link to another model.

Now run the following commands to prepare our database for our blog posts.

$ python manage.py makemigrations blog
$ python manage.py migrate blog

2 blog_migration

Django admin:
Let’s open the blog/admin.py file and replace its content with this:

from django.contrib import admin
from .models import Post

# Register your models here.

This file is responsible for registering our model. If we have more then one model, we need to register all of them.

Now create a super user for our site. Provide the necessary infos –

$ python manage.py createsuperuser

Now run the server through –

$ python manage.py runserver

Open your browser and go to –

Give the user name and password and enter into the Django Admin dashboard.

3 django_first_post

Django URL
Django urls work with regular expression. From the URL, it evaluates the location string. You have to have minimum idea about regix to get through it. For our blog we will define urls inside django/blog/urls.py. To do so, we need to include this file path into our django/mysite/urls.py

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('blog.urls')),

Now create a file in django/blog/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),

In this url patterns, we have created four pages for our blog site, post_list, post_detail, post_new and post_edit. In url pattern for post_detail and post_edit, “post/(?P[0-9]+)” is the primary key. So the url may be post/10 or post/10/edit.

For each post url, we have to create corresponding methods in views. So, let’s create edit our views.py as follows.

from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm

# Create your views here.
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})

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

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            return redirect('blog.views.post_detail', pk=post.pk)
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            return redirect('blog.views.post_detail', pk=post.pk)
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

From line 1 to 4 we have imported our classes.

From line 8 to 11 we have defined our post_list page. Line 10 query ordered by published date. And line 11, return the rendered page for post_list with posts.

Line 14 to 16 defines post_detail. Line 15 is a little check of if the post exists or not.

Line 18 to 29 is the explanation of post_new. This method works for the new post submission. If the form is valid then, the post will be saved to our database with the post, author and publish date. Otherwise the post form will be re-appears, From line 19 to 29.

Line 31 to 43 defines post_edit method for our existing post. Here also we have checked, if the post exists or not and then go for saving our edited post, just like before.

Now we have to create a form class to handle our new and edited posts. So, create a new file forms.py in the same folder.

from django import forms

from .models import Post

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text',)

In this file we have created a PostForm class for our form posting. And we have defined title and text fields as editable.

Django Templating:
Now let’s go for our html templates to see our post view, new post submission and editing the post. So, create two folders “templates/blog” inside django/blog.

Django supports templating for viewing. So, first of all we need to create a base template for all of our pages. This base template contains all the basic html code with some additional Django templating language.

So, now create a file named base.html in blog/templates/ folder.

        <h1><a href="/">Django Blog</a></h1>
        {% if user.is_authenticated %}
        <a href="{% url 'post_new' %}">Add</a>
        {% endif %}
            {% block content %}
            {% endblock %}

From line 4 to 6, we have checked if the user is authenticated or not. Only authenticated users can add new post.

Line 11 and 12 is the block for the body content. The content of this section may vary depends on your need.

Now let’s create our first landing page post_list.html inside same folder and edit it as follows.

{% extends "blog/base.html" %}

{% block content %}
    {% for post in posts %}

            <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
                {{ post.published_date }}
            <p>{{ post.text|linebreaks }}</p>
    {% endfor %}
{% endblock content %}

In line 1 we have extended our base template.

Line 3 to 14 is the content of our body. Here, we just loop through our all post and display the content of the title, published date and body.

In line 7 we have created a link for the detail of the post. Line 11 displays the portion of content of the post. When the reader clicks on the post title, he will see the detail of the post in post detail page.

For our post detail, we need to create post_detail.html in the same folder.

{% extends "blog/base.html" %}

{% block content %}
    <div class="post">

        <a href="{% url 'post_edit' pk=post.pk %}">Edit</a>
        <h1>{{ post.title }}</h1>
        {% if post.published_date %}
                {{ post.published_date }}
        {% endif %}
        <p>{{ post.text|linebreaks }}</p>
{% endblock %}

Just like before, line 1 extends the base template. And rest of the code is for content of our page.

In line 6, we have added one link for edit of the post.

Now let’s create our edit page named as post_edit.html in the same folder.

{% extends "blog/base.html" %}

{% block content %}
    <h1>New post</h1>
    <form method="POST">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
{% endblock %}

All the codes are almost same as before. There is a usual form submission fields. Here we have done a little security check, by giving csrf_token inside our form. It is a Django built in feature for it’s safety.

We are all done. Now open console and write the following command to run the server.

python manage.py runserver

Open your browser and go to

A full-featured Django blog is ready to go.

Ohhh.. Almost forgot to mention. Our blog is not good looking, because we have not added any styling. So, for the beautification, we can add all of our CSS and JS files inside base.html file and you will be ready to use all the classes and ids, as usual.

You can download, the whole project code from my github account.

Happy coding… 🙂

Blog with Django

One comment to “Blog with Django”

Leave a Reply

Your email address will not be published.