How To Create A Blog Using The Django Framework

In this tutorial, we are going to create a complete blog website using Django framework step by step. So, let’s get started.

Django is a web framework of Python and it is one of the very easiest back-end frameworks to learn. Before you get started, you should have some prerequisites to follow this tutorial smoothly. Here are they:  

  •  Front-end Basics – You should be familiar with at least the basics of HTML and CSS.
  •  Python Basics – You should be familiar with the syntax of Python and the working of the language.

Installing Django

Let’s start the project by installing Django in your system. If you already have Django installed, then skip this part.

To install Django on Windows, you just open your command prompt (CMD) and type in the following command and hit enter.

pip install django

To install Django on either MAC or Linux, open your command line and type in the following command and hit enter.

pip3 install django

That’s it. The system will automatically download and install Django on your system.

Also, you need to have an IDE (Code editor) to follow along with this tutorial. For this project, I’m using the Atom editor.

Now we have everything ready. I divided the entire project into 7 digestible steps so that you can follow along with me without getting overwhelmed. So, let’s start the project right away.

Step.1: Start the project and app

Create a new folder on your Desktop. I named my folder ‘BlogProject‘. Open your command line (CMD) and navigate to that folder.

cd Desktop

cd BlogProject  

Now, create a new project called ‘blog’. Type in the following command and hit enter to do so.  

django-admin startproject blog  

Navigate to the ‘blog’ folder and start a new app called ‘articles’.  

cd blog

python manage.py startapp articles    

If you are on MAC/Linux, type in python3 instead of python.   Now, let’s do the migration.  

python manage.py migrate  

Finally, we can run the server using the following command.  

python manage.py runserver

start blog project

Copy the URL you get and paste it on a new tab of your web browser. Hit enter and you will see a rocket if everything is correct.  

blog project started successfully

Now, open your IDE ( I’m using Atom). Open the project folder (blog) on your IDE. Go to settings.py inside the blog folder. Add the name of the app we created in the INSTALLED_APPS list.  

blog installed apps

Step.2: Create the models

In this step, we are going to create database models. We are creating a blog, so we need three things: author, title and body. So, we need to create three fields in our model to input these three things.  

We set the author as a ForeignKey so that the author can write multiple articles(many-to-one relation). So, open models.py and paste the following code there.

from django.db import models

class Article(models.Model):
    author = models.ForeignKey('auth.User', on_delete = models.CASCADE,)
    title = models.CharField(max_length = 100)
    body = models.TextField()
    def __str__(self):
        return self.title

We just created a class called ‘Article’ which is our model. The author field is set as a foreign key using the ForeignKey() method. Whenever we use this method, we have to mention ‘on_delete’ argument.

We have to set it as models.CASCADE, so that whenever we delete something, it will take care of that. The first parameter of this method is ‘auth.User’.   

The ‘auth’ is kind of a default way of handling user authentication in Django. For the title, we used a character field with 100 maximum characters and for the body, we used a text field.  

The __str__ method is used to display the title as the object name in the admin panel.

Now, you have created your model. Let’s go to admin.py file and register your model.

from django.contrib import admin
from .models import Article

admin.site.register(Article)

Step.3: Setting Up the Admin

Open your command line and inside the ‘blog’ folder, type in the following command.  

python manage.py makemigrations articles  

If you are on MAC/Linux, type in python3 instead of python. After that, type in the following command.  

python manage.py migrate articles  

Now, it’s time to create our user to log into the admin panel.  

python manage.py createsuperuser  

After that, create a user by typing in your username, email, and password. The superuser will be created successfully.

Now, let’s run the server.  

python manage.py runserver

blog runserver

Copy the URL and paste it on a new tab. Add ‘/admin’ to the URL and let’s check whether our admin is created successfully or not.  

blog admin url in django

Now, log in to the admin area using your id and password. Then you will find an interface like this.  

django admin interface

  Now, you can click the add button in the articles area to add new articles to your blog. Let’s add a few articles and save them.  

Step 4: Setting up the URLs

Now, go to the urls.py file and make the following changes to the code at the bottom portion of that file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('articles.urls')),
]

We mentioned the articles.urls file but that does not exist there. But before that, we need to create the views. So open views.py and create your views there.

from django.views.generic import ListView
from . models import Article

class ArticleListView(ListView):
    model = Article
    template_name = 'home.html'

We just created an ArticleListView in our views.py file. Now let’s create a file named ‘urls.py’ inside the articles folder. Copy and paste this piece of code there.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.ArticleListView.as_view(), name='home'),
]

Now, it’s time to create our templates folder. Create a new folder called ‘templates’ inside the blog folder (which is the project folder, not the inner folder). Inside that folder, create a new file and name it as ‘home.html’.  

Now, go into settings.py and we need to configure our templates. There is a list called TEMPLATES in that file. Make the following changes to the DIRS there.

'DIRS': [os.path.join(BASE_DIR, 'templates')],

Step 5: Setting up the home page

Now, open the home.html file and paste the following HTML code there.

<!DOCTYPE html> 
<html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>My Blog</title> 
</head> 
<body>
     <header>
       <h1> <a href="">My Personal Blog</a> </h1>
     </header>
     <div class="container">
       {% block content %}
         {% for i in object_list %}
             <div class="article">
             <h3><a href="">{{ i.title }}</a></h3>
               <p>{{ i.body }}</p>
            </div>
         {% endfor %}
        {% endblock content %}
     </div>
 </body> 
</html>

Note the syntax here. Everything that we need to fetch from the database is written inside the {% block content %} section.

This section ends at {% endblock content %}. All the articles are fetched one by one using a ‘for loop’.

I am not talking much about the HTML part since I assume that you already know the basics of HTML and also, this is a tutorial that focuses on the backend rather than the design of the page.

Step 6: Including static files

Let’s see how we can include static files like CSS file to our blog. For that, create a new folder called ‘static’ inside the blog folder (which is the project folder, not the inner folder).  

We have to link this in the settings file. So open your settings.py file and type in the following piece of code at the bottom, below the STATIC_URL part, which is already there.  

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Now, let’s add the styling to our blog. Create a new folder called ‘css’ inside the static folder. Inside css, create a new file and name it ‘style.css’.  

You can add your CSS styles here as you like. For simplicity, I am adding only a few styling to my blog. Paste the following code into the style.css file.

body{
background-color: #eee;
color: #222;
}

Now we need to link the CSS file in our home.html. So open home.html and add the following line of code between the <head> </head> tags.

<link rel="stylesheet" href="{% static 'css/style.css' %}"> 

Note that the href part is different from what we normally do with HTML and CSS. Here, we have to link in the Django way.

Also, we need to mention the home.html that we are using static files. So, paste the following line at the top of the home.html file.

{% load staticfiles %}

If you are running the latest version of Django then add, {% load static %} instead of {% load staticfiles %}.

Otherwise, you may get an error. Shout out to Pratik, who let me know this update via comment.

That’s it. Now you can modify and customize your blog as you like.

Step 7: Unique URL for an article

We need to set up separate URLs for articles so that when the users click each post on the home page, they will be redirected to another page which contains that article in detail.  

The thing is very easy. We need to create a separate template file for that and also create a separate view for that. First of all, open views.py and add the following class to that.

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'detail.html'

Also, don’t forget to import DetailView on the first line. So, modify the first line as follows.

from django.views.generic import ListView, DetailView

Next, we need to create a new file for the detailed article. So, create a new file called ‘detail.html’ inside the templates folder. Paste the following code snippet into the ‘detail.html’ file.

{% load static %}
 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="{% static 'css/style.css' %}">
   <title>My Blog</title>
 </head>
 <body>
     <header>
       <h1> <a href="">My Personal Blog</a> </h1>
     </header>
     <div class="container">
     {% block content %}
         <div class="details">
         <h2>{{ article.title }}</h2>
         <p>{{ article.body }}</p>
         </div>
     {% endblock content %}
     </div>
 </body>
 </html>

Note that we added {{ article.title }} and {{ article.body }} here. These will fetch our article’s title and body part into the page.

Now, we have to mention the URL to urls.py. So open urls.py in the articles folder and add the following line of code as the path.

path('article/<int:pk>', views.ArticleDetailView.as_view(), name='detail'),

The int.pk in this file indicates the primary key. pk stands for the primary key here. The database automatically gives a unique ID for each article. That unique ID is also called the primary key.

Now, open home.html and add the href link to the h3 article heading. So, modify the line that contains <h3> tag, inside the class article as follows.

<h3><a href="{% url 'detail' i.pk %}">{{ i.title }}</a></h3>

That’s it. Our blog is ready to run. Your server should be automatically reloaded by now.

Open your terminal (command line), copy the URL there and paste it on a new tab in your browser. You can see your project running on your browser.

How to create a blog using django

We can see that our Django blog is working perfectly. You can click and visit each article and it will function just like a normal blog.

This is just a basic blog with no styles or attractive design. But, now you know how to create a blog from the back end using Django.

You can create your own beautiful good looking blog using these steps and applying your front end skills on top of it.

I know you may fall into some errors while doing this project. Here is a link to my GitHub repository, where you can find all the files and code. Make sure that you haven’t messed up with the file structure.

Try to fix the errors by debugging it by yourself. If you need any help, please feel free to ask your doubts in the comments section down below.

I hope you like this article. Let me know your thoughts on this article and also, share it with your friends so that someone else could benefit from this tutorial.

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

50 thoughts on “How To Create A Blog Using The Django Framework

    1. There are a lot of materials available online. I hope this video will help you learn the fundamentals of Django: https://www.youtube.com/watch?v=F5mRW0jo-U4&t=16s

    1. Hey, Could you tell me what the error is? I assume that your error might be “template does not exist”. If that is the case, I think you might have created the ‘static’ and ‘templates’ folder inside the wrong directory. There are two folders called ‘blog’. You need to create ‘templates’ and ‘static’ folders inside the project folder (blog), not in the other folder. I hope that’ll help you. If not, let me know.

      If you need more help, you can find out the source code here: https://github.com/AshwinJoy/Django-Projects/tree/master/blog

  1. My admin pages work fine but I’m now getting an error with this URL: http://127.0.0.1:8000/

    Here’s the error:
    **************************************************
    Page not found (404)
    Request Method: GET
    Request URL: http://127.0.0.1:8000/

    Using the URLconf defined in website1.urls, Django tried these URL patterns, in this order:

    admin/

    The empty path didn’t match any of these.
    **************************************************

    My code in urls.py for website/blog:
    *********************************************
    from django.contrib import admin
    from django.urls import path, include

    urlpatterns = [
    path(‘admin/’, admin.site.urls),
    path(‘ ‘, include(‘articles.urls’)),
    ]
    *********************************************

    I am learning and this seems to be a good way to learn how everything works and how I can debug issues. I suspect the “include” is not bringing in urls.py that exists in the articles folder. Is there a way for me to go deeper into debugging this without you just stating what the problem is?

    1. I believe my folder structure got messed up. I’m going to go through these steps again. It would be helpful if you posted the final folder structure and files that should exist in each folder.

      1. I think probably the issue might be with the folder or file structures. I’ve put all the files in this GitHub directory: https://github.com/AshwinJoy/Django-Projects/tree/master/blog
        I hope you can find out how the files are located from this link.

        For debugging, it will be often helpful if you copy the error and google it. Probably, StackOverflow or some other websites might help you. I can’t tell you exactly what the error is as I can’t see your files. But, most probably, you might have messed up the file structure.

      2. So, i put the static and template folders in the “inner” blog folder by mistake but moving them out the the parent blog folder doesn’t get rid of the error. Still working on this…

        1. I will look at your files and try them. I see these errors in the terminal window:

          (djangoenv) C:\Users\JimW\myDjangoProjects\website1>python manage.py runserver
          Watching for file changes with StatReloader
          Performing system checks…

          System check identified no issues (0 silenced).
          November 21, 2019 – 11:25:51
          Django version 2.2.5, using settings ‘website1.settings’
          Starting development server at http://127.0.0.1:8000/
          Quit the server with CTRL-BREAK.
          Not Found: /
          [21/Nov/2019 11:26:05] “GET / HTTP/1.1” 404 2024
          Not Found: /favicon.ico
          —————————————-
          Exception happened during processing of request from (‘127.0.0.1’, 59184)
          Traceback (most recent call last):
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\socketserver.py”, line 650, in process_request_thread
          self.finish_request(request, client_address)
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\socketserver.py”, line 360, in finish_request
          self.RequestHandlerClass(request, client_address, self)
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\socketserver.py”, line 720, in __init__
          self.handle()
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\site-packages\django\core\servers\basehttp.py”, line 171, in handle
          self.handle_one_request()
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\site-packages\django\core\servers\basehttp.py”, line 179, in handle_one_request
          self.raw_requestline = self.rfile.readline(65537)
          File “C:\Users\JimW\Anaconda3\envs\djangoenv\lib\socket.py”, line 589, in readinto
          return self._sock.recv_into(b)
          ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
          —————————————-

          1. Just compare your files with my code. I hope you’ll find out the error.
            What error is showing on the webpage? Is it the same as it was before? Try to run the server again, and see whether there are any errors showing on the webpage.

          2. Thanks for the files. I substituted your files in place of mine until I found the issue. In step 4, the following line has a space which needs to be removed for this tutorial to work:
            Wrong: path(‘ ‘, include(‘articles.urls’)),
            Correct: path(”, include(‘articles.urls’)),

            Thanks for your help!

    1. You can use this CSS styling to add a background image to your body tag:
      body {
      background-image: url(“image.jpg”);
      }

      Learn more about CSS, and you’ll be able to a lot of designing with your website.

    1. If you just want to add images from the front-end itself, you can use the tags in HTML.

      If you want to do it using the Django-way (i.e., from the backend), check out this link: https://wsvincent.com/django-image-uploads/

      I hope it will teach you how to upload images and files in Django.

  2. i am unable to write the password in the createsuperuser on command prompt which is discussed in step 3 so that i cannot proceed further pls help..

    1. I think you’re having this issue because you can’t see the password you are typing. It’s fine, you might not be able to see what you type in. Just enter your password and type enter, and see what happens. Hopefully that’ll solve the issue. If that’s not the issue,let me know. Thank you.

  3. I do not get the option for adding articles in my admin panel. There is an option for only authentication and authorization. Can you please explain what could be the problem ?

    1. I think you might have missed something from steps 1-3. Check whether everything is done correctly. If you’ve done, you’ll see an option for adding articles in your admin panel at step 4.

  4. Amazing Tutorial!!
    If you are running newer version of Django then add,
    {% load static %}
    Instead of
    {% load staticfiles %} in home.html and detail.html
    Otherwise you may get an error.

    1. Did you link the CSS with the HTML file? If you did, then try to remove the cache from your browser, and try loading the page again.

    1. You might have created the ‘static’ and ‘templates’ folder inside the wrong directory. There are two folders called ‘blog’. You need to create ‘templates’ and ‘static’ folders inside the project folder (blog), not in the other folder. If that’s not the issue, check out the source code to figure out the mistake: https://github.com/AshwinJoy/Django-Projects/tree/master/blog

  5. Hi,
    After running migrations, I’m getting an error ‘django.db.utils.OperationalError: no such table: auth_user’
    when I run command ‘python manage.py createsuperuser’

    Can someone please help me with troubleshooting this issue??

    I’d greatly appreciate it, thank you.

    1. Hi,
      Try to manually check the migrations folder inside your app.If you can see the migrations folder, then delete everything inside the folder except the init.py file.

      If you do not find a migrations folder, just create one manually. After that, try to rerun the commands in command line.

      Hope that helps. Let me know if it doesn’t work.

  6. Password (again):
    Error : Blank passwords aren’t allowed.
    This is the message that show when I type password again and again

    1. The command prompt won’t show the password that you are typing in. Just type your password, repeat the same password when prompted, and you should be fine.

  7. Hi, You post is really awesome and it has much detailed information about Django.

    I am quite newbie in django. I want to create a site which takes blog post data from the external JSON file and create blog post & publish automatically.
    So, could you tell just overview about what i exactly need to do. So that i can implement them.

    Thanks

  8. Has anyone had any issues with playing with the static files, that then have zero effect on the website? I’ve been trying to customise my background colour and have had zero success.

    Could this be an issue with file structure? I’ve played around with it a bit, it continues to work but I can’t customise the site at all. I have the latest version of Django.

    Is this a CSS problem? Or am I not pointing Django at the correct files?

    1. I guess that could be an issue with the cache files in your browser. Try to clear the cache and reload the page. Hopefully, it will solve the issues.

      1. Hey Ashwin, I just tried it and it didn’t work.

        I did notice something with VSC, when I load up the blog project it shows articles inside of the blog folder. Whereas when I just load up blog, it doesn’t show articles. Somehow the site runs fine, though it might have something to do with the CSS file?

        Thank you

  9. (djangoenv) C:\Users\IIIT-rgukt\Desktop\BlogProject\blog>python manage.py makemigrations articles
    No installed app with label ‘articles’. im getting this error

    1. Programming is all about problem-solving and googling. Try to solve problems by yourself. You’ll improve your skills if you do so.

  10. I followed the steps you mentioned above. But I am not able to login to admin page using correct credentials. Getting “Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.”

    1. Maybe you need to type in the username and password correctly. The command line will not show them as you’re typing in. Just type in the credentials correctly even though they aren’t visible.

  11. I’m having an error

    TemplateDoesNotExist at /
    home.html, blog1/article_list.html
    Request Method: GET
    Request URL: http://127.0.0.1:8000/
    Django Version: 3.0.8
    Exception Type: TemplateDoesNotExist
    Exception Value:
    home.html, blog1/article_list.html
    Exception Location: C:\Users\Workspace\PycharmProjects\blogg\venv\lib\site-packages\django\template\loader.py in select_template, line 47
    Python Executable: C:\Users\Workspace\PycharmProjects\blogg\venv\Scripts\python.exe
    Python Version: 3.8.2
    Python Path:

  12. Hi Ashton,
    I already created the admin page, but I can’t login by the right username and password. Then I go back to create
    User again. I have used different simple user and password to make sure I type right. I still cannot login. I think I have the same issue as Dhanush
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts