Adding Featured Image in Blog Posts - Django Blog #5

Hello Internet Programmers, today we are adding featured image in blog posts. Featured image are important to attract people to visit your blog right. So, activate your virtual environment and let’s start.

ImageField in model

To add image in our blog post we need to add ImageField to our post model to store in database.

But first install Pillow python module in your virtual environment because we are working with image,

python -m pip install Pillow

Now open models.py of blog application and make following change,

class Post(models.Model):
    ...
    image = models.ImageField(upload_to='featured_image/%Y/%m/%d/') #this
    ...

Now run the migrations,

python3 manage.py makemigrations

But get this error, just select 1 option and add '' to provide value for each post.

This is asking because all other post don’t have image value so by default we provide null to all.

Now migrate,

python3 manage.py migrate

Run development server using python3 manage.py runserver and open http://127.0.0.1:8000/admin/blog/post/add/

image field in django admin

image field

Now open any existing post and try to add image to it. No open vs code you noticed inside media folder featured_image folder is created. Just open it you noticed the image which you uploaded through Django admin image field of post model.

media

media files

Displaying Image in HTML template

We uploaded the image in the database right. Let’s display it in our HTML template so everyone see that.

First open post_list.html and edit img tag like following code,

<!-- featured image --> 
<img src="{{ post.image.url }}" class="rounded featured-image-list" alt="{{post.title}}">

Add following css in style.css for setting a height and width for image,

.featured-image-list{
    object-fit: cover;
}

Now open http://127.0.0.1:8000/ and refresh the page,

I added image to all post.

featured image in blog post list

featured image

You it’s looks awesome right.

Now open post_detail.html to add image in single post and edit img tag like following code,

<!-- featured image --> 
<img src="{{ post.image.url }}" class="rounded" alt="{{post.title}}">

Now open any post and refresh the page,

featured image in post

featured image in post

Looks amazing right.

That’s it for this tutorial. Share this tutorial with your friends and stay awsome.

GitHub Link: https://github.com/SoniArpit/awwblog

Previous: Integrating CKEditor in Django Admin and Rendering HTML in a template – Django Blog #4

Next: Adding Django Threaded Comments in Blog – Django Blog #6