Django Blog Tutorial – Make A Simple Blog

In this tutorial, we’ll discuss about how to make a simple Blog in Django 2.

Our blog will have TITLE, PICTURE, DESCRIPTION (Body), DATE.  There will be two pages, one for showing all the blogs at one place with less information and the second one to show each blog in detail.

Prerequisite

  • Django 2.0 or above should be installed.
  • Create a project

Django Blog Tutorial

Creating App

I have created a project named as blog_project. Now we’ll create an app for Blog, So in future, if we need to use Blog in other projects then we can use this app.

To create an app, open terminal and navigate to your project folder.

Type the command below:

python manage.py startapp blog

Now add a path for our newly created app in settings.py. Open settings.py and look for INSTALLED_APPS list.

INSTALLED_APPS = [
    'blog.apps.BlogConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Add these lines in the last.

MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/pics/'

I have added a path for Blog as first item of the list INSTALLED_APPS. If you’re thinking, from where this BlogConfig have came from instead of Blog, then navigate to your blog app folder and open apps.py file. Here you can see a class name as BlogConfig. This is what we add in settings.py while adding path for app in settings.

Creating Model

Open the models.py in your blog app folder and edit it as

from django.db import models
class Blog(models.Model):
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField()
    image = models.ImageField(upload_to='images/')
    body = models.TextField()

    def summary(self):
        return self.body[:100]
    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %e, %Y')
    def __str__(self):
        return self.title

So I’ve created a model to store title, publishing date (pub_date), picture (image) and description (body).  I’ve also created some functions inside the model.

  • Summary: summary functions will return us the short info about a blog. For example, on the page where we will show all the blogs, we’ll not display the whole body of each blog. Instead of it we’ll use short info about that blog.
  • pub_date_pretty: It will return you the date in this format – Sep 26, 2018, which looks more user friendly then the default date format.
  • __str__: It is an inbuilt function, I’ve overridden it to return the title instead of object index in the admin panel. You’ll see the result in the admin panel.

Now in the last, open the admin.py file to register your blog to show on the admin panel and the following lines.

from django.contrib import admin
from .models import Blog
admin.site.register(Blog)

Edit urls.py

Now edit your main urls.py file and add two url path. First for the homepage where all our blogs will display and second one is for detail page, where each of the blog in detail will be shown up.

from django.contrib import admin
from django.urls import path
from blog import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.allblogs , name='allblogs'),
    path('<int:blog_id>/', views.detail, name="detail"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Here we’ve added two paths, one for showing all the blogs and another for showing a particular blog in detail. The empty string in path shows that it is home page and will call views.allblogs function and ‘<int:blog_id>/means it will take integer after domain name and call views.detail function.

Edit views.py

Open the views.py inside your app blog folder and edit it as:

from django.shortcuts import render, get_object_or_404
from .models import Blog

def allblogs(request):
    blogs = Blog.objects
    return render(request, 'blog/allblogs.html', {'blogs':blogs})

def detail(request, blog_id):
    blogdetail = get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/detail.html', {'blog':blogdetail})

Firstly we are importing some of modules to work with,

  • render: to return a template on requested.
  • get_object_or_404: to get the stored objects from database.
  • Blog: to get the Blog’s objects we have to use this model name.

After that, we have two functions allblogs() and detail().  allblogs function will get all the stored objects from database of Model Blog and return the template along with all the objects of database.

detail function have an extra parameter inside it – blog_id, this blog_id will be used to get a particular object from the database according to the primary key and the primary key is our blog_id.

After that this function will return user another template along with the particular object.

Create Templates

  • allblogs.html: create a folder templates inside the blog app, then create another folder inside the template as the same name as app blog, now create allblogs.html here.

So our project directory will look like this:

Django Blog Tutorial 1

And add this code into you allblogs.html:

<!doctype html>
<html>
	<body>
      		<h1>My Blog</h1>
      		<br /> <br />
     		 <h2>Latest posts</h2>
     		 <hr/>
     		 {% for blog in  blogs.all %}
    			<a href="{% url 'detail' blog.id %}">  <h3>{{ blog.title }}</h3></a>
   			   {{ blog.pub_date_pretty }}
   			   <br />
    			  <img src = "{{ blog.image.url }}" height=200 width=200/>
  			    <br />
    			  <p>{{ blog.summary }}</p>
     		 {% endfor %}
    
  		&copy; My Blog,  {% now "Y" %}
	</body>
</html>

In above code, we’re looping through all the blogs (sent from allblogs function in the views) and printing title of the blog as link, date, image and short summary.

When user click on the title, he/she will be navigated to the URL having name detail.

  • details.html: create details.html in the same directory as above and edit it as:
<!doctype html>
<html>
  <head>
    <title> {{ blog.title }}</title>
  </head>
<body>
      <h1> {{ blog.title }}</h1>
          <p>{{ blog.pub_date }}</p>
      <hr />
      <br />
      <center>
      	<img src = "{{ blog.image.url }}"  height=”300” width=”400”/>
      </center>
<br />
      <br/>
      <p>{{ blog.body }}</p>
      &copy; Indrajeet,  {% now "Y" %}
  </body>
</html>

In above code, we’re just printing the title, publishing date, image , full summary of the particular blog.

Testing

First migrate unapplied migrations, open your terminal and navigate to the project folder and run:

python manage.py migrate

Then run server by typing:

python manage.py runserver

Now open browser and open admin panel (http://localhost:8000/admin/) and login to add some data into our databases.

In case, you don’t have the admin username and password, just stop your server and type this command:

python manage.py createsuperuser

And create admin account. Then reload the server and open admin panel to add some blog posts.

Django Blog Tutorial 2

Django Blog Tutorial 3

 

Django Blog Tutorial 3

As you can see I have added three blogs. Now let’s open our website’s homepage.

Django Blog Tutorial 5

After clicking on any title:

Django Blog Tutorial 6

Its working. That’s the simplicity of Django. We can make it more attractive by adding some bootstrap or css.

If you’ve any query related with this article, please let us know in comment box.

4 thoughts on “Django Blog Tutorial – Make A Simple Blog”

Leave a Comment

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