In this tutorial, we are going to create a complete blog website using the 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.
The prerequisites are Front-End Basics (You should be familiar with at least the basics of HTML and CSS) and 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
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.
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.
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
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.
Now, log in to the admin area using your id and password. Then you will find an interface like this.
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 ‘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
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 files in 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 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;
}
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. 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 that 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 the <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.
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.
How to gain knowledge about all these models, views in django to learn quickly
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
Great way to exercise my django skills. Thanks!
Cheers.
Do you have the source code available? I’m getting an error and not sure why. Thanks.
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
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?
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.
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.
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…
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
—————————————-
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.
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!
I got an error
Password field can’t able to type
It’s going type password again
Brother please tell me how can i apply background image for my page
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.
please tell me how can i add an image on my blog
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.
Good tutorial!
Thanks.
It show only first page
Written
My personal blog
Did you add articles from the admin panel(back-end)?
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..
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.
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 ?
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.
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.
Thanks for the comment.
Hi,
Why is my styling not reflected even after changing the style.css?
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.
I linked the file, file path is correct & cleared the cache. Nothing worked.
it is working now, it is my settings file static_dir issue.
Great! Keep coding!
exception has been raised.. it says template does not exist at home.html..why is that ?
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
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.
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.
Hi Ashish, It’s great that you’re creating a django project by yourself. I think you might have missed something in step 7. I think it might be because the primary key is not coming properly in the url.
Password (again):
Error : Blank passwords aren’t allowed.
This is the message that show when I type password again and again
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.
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
Learn how to read data from external JSON files. You can use the json module in Python for that.
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?
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.
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
(djangoenv) C:\Users\IIIT-rgukt\Desktop\BlogProject\blog>python manage.py makemigrations articles
No installed app with label ‘articles’. im getting this error
Programming is all about problem-solving and googling. Try to solve problems by yourself. You’ll improve your skills if you do so.
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.”
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.
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:
Please check the given GitHub repository link and verify whether the code and the file structure is correct.
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
Hi Ashwin
My django Blog page is open correctly but it is not showing full article of home and detail file.
Hi ! Ashwin sir,
First of all thank you so much for creating such a informative blog….
I created my first ever project in Django. So I am really happy with this.
The only problem I faced during this project that you said–
add {% load static %} at the top of your html files. It gave me errors.
fortunately I came up with an idea and I added them inside my Doctype line as follows
and then now everything is working like awesome……..
thank you so much.
Awesome man!
hie , i am creating a blog using django… i can add and edit blogs in my django admin. when i go to my site, it shows all the blogs that i have added but if i open them, every blog shows the content of the first blog that i have added.
Like this blog post of yours
how can i make a blog post of images located at a random position in the post
Hi Ashwin
Getting the below Error
File “C:\Users\Rahul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\template\loader.py”, line 47, in select_template
raise TemplateDoesNotExist(“, “.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: home.html, articles/article_list.html
[24/Aug/2023 19:17:49] “GET / HTTP/1.1” 500 84440
same thing
I am not able to display the blog content on my homepage its getting added in admin panel but its mot reflecting on development server
Hii Ashwin Sir,
Getting this error\
[25/Aug/2023 13:35:26] “GET / HTTP/1.1” 200 532
[25/Aug/2023 13:35:26] “GET /static/css/style.css HTTP/1.1” 404 1798