Building A Blog Application With Django

In this tutorial, we'll build a Blog application with Django that allows users to create, edit, and delete posts. The homepage will list all blog post
8 min read

 It's time to convert my literary blogs into tech blogs. I have been inspired by my How to create Stock correlation matrix, which has received many responses by you' all. So let’s start a multi-part tech blog series!

To achieve this goal, I used Django, an extensible web framework that is built on top of Python, which I'm already familiar with. This article is for people with similar goals who are new to Django, Python, and or web frameworks, who are looking for projects to build out in the new reality we are finding ourselves in.

Building A Blog Application With Django


SETUP

We'll set up Django, your project directory, and your virtual environment. You'll need the following in the following versions:

pipenv (version 2019.11.26)
python (version 3.7.5)

You can download pipenv here. If you are working off a brand new set of installs, you can download Python here, and pip (package handler that installs packages for Python) here.

INSTALL DJANGO

This will install that version of Django into your virtual environment using that version of Python.

pipenv --python 3.6.5 install django==3.0.6

SETTING UP DJANGO

Navigate to place where you want to create your project on your CMD, and enter this command there:

django-admin startproject Project_Name

Navigate to that folder in the terminal and ls to verify you're in the right place. You should see manage.py, a key file in Django projects.

Run the following to migrate changes, a necessary command to sync your project files in Django: python manage.py migrate. You should see in the terminal a bunch of files are committing. Don't worry about that for now. Next run python manage.py runserver to get it up and running.

You should see in the terminal the URL is http://127.0.0.1:8000/. Go there in your browser and see for yourself that your project is initialized! You should see this default screen:

Building A Blog Application With Django

If you see that it worked and you're well on your way to customizing your project! If you don't see that, please comment and I will answer any questions you have.

CREATE SUPERUSER

You’ll need to create an admin user to use Django Admin to manage your blog posts and such. In the terminal, run this command and follow the prompts to create that user:

python manage.py createsuperuser

You should see that your user account was created successfully. Now navigate to http://127.0.0.1:8000/admin with your server running to log in and see the Admin view.

You should see this upon successful login:

Building A Blog Application With Django

RUNNING ON DIFFERENT PORTS

If you want to change the server's port, then you need to pass it as a command-line argument:

$ python manage.py runserver 1602

The same goes for the IP address:

$ python manage.py runserver 0:8000

This will run on IP address: 0.0.0.0

CREATING FIRST APP

Right, are we here on app development course, NO sorry but these are the nomenclature that we have in Django. Django works off of the notion of apps, which you can think of as micro-functionalities within your site. In a fully built out project, the blog of your website may be just one such app. You want to make apps that are able to plug and play ideally across projects so you can recycle code. That way, let’s say in the future you make another website and you want a fully working blog to just pop into one of the subdomains of the site.

With that said, I'm going to assume you want the following apps as a default: a home page (the blog article list view), and an about page. Realistically, the about view is a more static view and doesn't necessarily need dynamic updates, but it might one day! Run the following commands to create those apps.

python manage.py startapp blog

CREATING A VIEW

Let’s write the first view. You need to open the views.py file in your home/ directory. Let's create a simple view as follows:

from django.http import HttpResponsedef index(request):
  return HttpResponse("Welcome to home page.")

To call the view, we need to map it to a URL. Let's create a new file (urls.py) and put in the following code:

  from django.urls import pathfrom . import
  viewsurlpatterns = [
     path('', views.index, name='index'),
  ]
  

Now we have set up the URLs for the blog app, but this isn't connected to the main Django application. So let's do that by going into the main urls.py file as follows:

  from django.contrib import admin
  from django.urls import include,path
  pathurlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
  ]

Now that we have connected a view to the URLs, you are able to check it out in your browser. Simply rerun the development server to do so:

$ python manage.py runserver

Go to http://localhost:8000/blog/ in your browser, and you should see the text “Welcome to home page.”

MODELS

We are going to define our models for the blog app. We will create one model and label it “Article” or “Blog Post” (feel free to decide this yourself). Python classes represent these concepts. Edit the blog/models.py file so that it looks like this:

from django.db import modelsclass 
Post(models.Model):
  title= models.CharField(max_length=200)
  content= models.CharField()
  pub_date = models.DateTimeField('date published')

We can see that every class inherits the class of Model. Each model has several class variables, each of which represents a database field in the model. To get more information about the Model class, I would recommend that you refer to the official Django documentation.

ACTIVATE THE MODEL

That small bit of model code gives Django a lot of information. With it, Django can:

Create a database schema for this app.

Create a Python database-access API for accessing the Post objects.

To migrate, simply run the command:

$ python manage.py makemigrations blog

You should see an output similar to this:

Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model Post

By running makemigrations, you're telling Django that you've made some changes to your models.

To migrate your database for the last time, run the migrate command as follows:

$ python manage.py migrate 

TEMPLATES VIEWS

Django as a framework utilizes the Model View Template (MVT) software design pattern. There are more details in that link, but basically when you go to a URL, Django checks for the pattern that matches that URL and what template and model it needs to render to the browser. It renders the template (think page structure) with the model's data.

HOW TO CREATE YOUR TEMPLATE

First, create a new view in blog/views.py:

def post(request, post_id):
  return HttpResponse("You're looking at post %s." % question_id)

Now configure the urls.py to be able to use this view:

  from django.urls import path
  from . import views
  urlpatterns = [
      path('', views.index, name='index'),
      path('<int:post_id>/', views.post, name='post'),
  ]
  

Take a look in your browser at /blog/<post_id>/. If you have added posts in the admin dashboard, then this ID will be displayed. Now, let’s create a view that really displays the blog posts. In the blog/views.py, we add the following code:

  from .models import Post
  def index(request):
     latest_post_list = Post.objects.order_by('-pub_date')[:5]
     output = ', '.join([q.question_text for q in latest_post_list])
     return HttpResponse(output)

There's a problem here, though: The page's design is hard-coded in the view. To rectify this, we will create a template. First, create a directory called templates in your blog directory. Django will look for templates in there.

Put the following code in that template called index.html:

{% if latest_post_list %}
  <ul>
  {% for post in latest_post_list %}
      <li><a href="/blog/{{ post.id }}/">{{ post.title }}</a></li>
  {% endfor %}
  </ul>
{% else %}
  <p>No posts are available.</p>
{% endif %}

Now let's update our index view in blog/views.py to use the template:

  from django.http import HttpResponse
  from django.template import loader
  from .models import Post
  def index(request):
      latest_post_list = Post.objects.order_by('-pub_date')[:5]
      template = loader.get_template('blog/index.html')
      context = {
          'latest_post_list': latest_post_list,
      }
      return HttpResponse(template.render(context, request))
  

Conclusion

I hope you learned a lot from this beginner’s guide to setting up a simple web app in Django with Python. My aim in writing this article was to outfit you with the fundamentals of Django in Python, thereby empowering you with the ability to get curious and play around from there.

Feel free to leave any thoughts in the comments. Thanks and happy coding!

You may like these posts

2 comments

  1. second ago
    Excellent Post keep it bro.....
    1. second ago
      Thank You Sir