[Django]-Django Admin and ImageField dimension restrictions

3👍

With Django 2 and up one can use a far simpler approach to this.
Just remember the 2 Scoops of Django philosophy of FAT models. Use models.py and include a custom validation for the ImageField, one can then subsequently use it for any related ImageField for other models that you create. Consequently, forms and admin will naturally run this validation and output the errors

Example code

Insert this into a new file created under your app called validators.py

from django.core.exceptions import ValidationError
from django.core.files.images import get_image_dimensions

def image_restriction(image):
    image_width, image_height = get_image_dimensions(image)
    if image_width >= ??? or image_height >= ???:
        raise ValidationError('Image width needs to be less than 128px')

And then in your models simply import and include

from apps.assessment.validators import image_restriction

image = models.ImageField(
    validators=[image_restriction],
    upload_to='assessment_images'
)

1👍

You can override form for your ModelAdmin class and validate your image dimensions.

from django.contrib import admin
from django import forms
from django.core.files.images import get_image_dimensions

from .models import ModelWithImageField


class ModelWithImageFieldForm(forms.ModelForm):
    class Meta: 
        model = ModelWithImageField
        fields = '__all__'

    def clean_photo(self):
        photo = self.cleaned_data["photo"] 
        width, height = get_image_dimensions(photo.file)
        if width < 900 or height < 900:
            raise form.ValidationError("Improper size.")
        return photo


@admin.register(models.ModelWithImageField)
class ModelWithImageFieldAdmin(admin.ModelAdmin):
    form = ModelWithImageFieldForm

Leave a comment