I see a lot of people with Django apps that have image uploads are automatically resizing the images after they are uploaded. That is well and good for some cases, but I don't want to do this. Instead, I simply want to force the user to upload a file that is already the proper size.
I want to have an ImageField where I force the user to upload an image that is 100x200. If the image they upload is not exactly that size, I want the admin form to return as invalid. I would also like to be able to do the same thing for aspect ratios. I want to force the user to upload an image that is 16:9 and reject any upload that does not conform.
I already know how to get the width and height of the image, but I can't do that server-side until after the image is already uploaded, and the form is submitted successfully. How can I check this earlier, if possible?
A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields.
Just use isEmailAddressValid(address) to perform the validation. Since the question is about Django, this is the best answer.
The right place to do this is during form validation.
A quick example (will edit/integrate with more info later):
from django.core.files.images import get_image_dimensions from django.contrib import admin from django import forms class myForm(forms.ModelForm): class Meta: model = myModel def clean_picture(self): picture = self.cleaned_data.get("picture") if not picture: raise forms.ValidationError("No image!") else: w, h = get_image_dimensions(picture) if w != 100: raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 100px" % w) if h != 200: raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h) return picture class MyAdmin(admin.ModelAdmin): form = myForm admin.site.register(Example, MyAdmin)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With