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):
        return self.name
    

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="{{ my_model_instance.name }}">
    

Example: Displaying Images in a Django Template


{% for product in products %}
    <div class="product">
        <h3>{{ product.name }}</h3>
        <p>{{ product.description }}</p>
        <img src="{{ product.image.url }}" alt="{{ product.name }}">
    </div>
{% 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 = Image.open(self.profile_image.path)
            if img.height > 300 or img.width > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.profile_image.path)