Menu Close

How to upload multiple images to a blog post in Python Django?

To upload multiple images to a blog post in Python Django, we add a model for the images.

For instance, we write

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    body = models.CharField(max_length=400)
def get_image_filename(instance, filename):
    title =
    slug = slugify(title)
    return "post_images/%s-%s" % (slug, filename)  

class Images(models.Model):
    post = models.ForeignKey(Post, default=None)
    image = models.ImageField(upload_to=get_image_filename,

to create the Post and Images models.

And then we reference the post with the image in the Images model.

And we have the image file field.

We use the get_image_filename function to get the image path to save the image file to.

Posted in Python, Python Answers