Last modified: Sep 25, 2023 By Alexander Williams

Django ImageField Examples

Example: Using Django's ImageField in a Model

from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='images/')

    def __str__(self):

django filefield

Example: Adding ImageField to a Form

from django import forms

class MyForm(forms.Form):
    name = forms.CharField(max_length=100)
    image = forms.ImageField()

Example: Displaying an Image in a Django Template

<img src="{{ my_model_instance.image.url }}" alt="{{ }}">

Example: Displaying Images in a Django Template

{% for product in products %}
    <div class="product">
        <h3>{{ }}</h3>
        <p>{{ product.description }}</p>
        <img src="{{ product.image.url }}" alt="{{ }}">
{% endfor %}

Example: Resizing Images with Pillow

from django.db import models
from PIL import Image

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(upload_to='profile_images/', blank=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self.profile_image:
            img =
            if img.height > 300 or img.width > 300:
                output_size = (300, 300)