6

I wanted to upload files with limited extension on imagefield. So, how can I validate my image field for jpg,bmp and gif only. Also, which extension does image field take in by default?

pariwesh
  • 341
  • 4
  • 11
  • possible duplicate of [Django (audio) File Validation](http://stackoverflow.com/questions/6194901/django-audio-file-validation) – Timmy O'Mahony Mar 20 '14 at 14:10
  • The validation is pretty much exactly the same (just use the part that checks the extension). AFAIK, there are no default limits on what extensions are accepted. That's up to you to implement (using the linked duplicate question) – Timmy O'Mahony Mar 20 '14 at 14:20

1 Answers1

3

This is how I do it:

from django.utils.image import Image

# settings.py
# ALLOWED_UPLOAD_IMAGES = ('gif', 'bmp', 'jpeg')


class ImageForm(forms.Form):

    image = forms.ImageField()

    def clean_image(self):
        image = self.cleaned_data["image"]
        # This won't raise an exception since it was validated by ImageField.
        im = Image.open(image)

        if im.format.lower() not in settings.ALLOWED_UPLOAD_IMAGES:
            raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
                                          % ", ".join(settings.ALLOWED_UPLOAD_IMAGES)))

        image.seek(0)
        return image

Works for ModelForm as well.

Unit test:

from StringIO import StringIO

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.utils import override_settings
from django.test import TestCase


class ImageFormTest(TestCase):

    def test_image_upload(self):
        """
        Image upload
        """
        content = 'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00' \
                  '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
        image = StringIO(content)
        image.name = 'image.gif'
        image.content_type = 'image/gif'
        files = {'image': SimpleUploadedFile(image.name, image.read()), }

        form = ImageForm(data={}, files=files)
        self.assertTrue(form.is_valid())


    @override_settings(ALLOWED_UPLOAD_IMAGES=['png', ])
    def test_image_upload_not_allowed_format(self):
        image = StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
                         '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
        image.name = 'image'
        files = {'image': SimpleUploadedFile(image.name, image.read()), }
        form = ImageForm(data={}, files=files)
        self.assertFalse(form.is_valid())

Pillow will allow a bunch of image formats

nitely
  • 2,208
  • 1
  • 22
  • 23