Opened 14 years ago

Closed 2 weeks ago

Last modified 2 weeks ago

#18543 closed Bug (fixed)

Non image file can be saved to ImageField

Reported by: johnsmith Owned by: Goodluck Igbokwe
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords:
Cc: niwi@…, deprince@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

​https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield

Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.

I was trying to find out the exact exception that would be raised if a file is not an image and it appears that no such image validation is done. So I did a test, with a model such as this

class Image(models.Model):
    caption = models.Charfield(max_length=60)
    image = models.ImageField(upload_to='somewhere')

I tried this

f = django.core.files.base.ContentFile('not an image')
i = myapp.models.Image()
i.caption("This should throw an error but doesn't")
i.image.save('bar.jpg', f)
i.save()

I don't get any errors and the file is saved. Maybe I'm doing something wrong but from what the docs say I'm expecting to be prevented from doing this.

From pip freeze
Django==1.4
PIL==1.1.7

Change History (20)

comment:1 by Andrei Antoukh, 14 years ago

Cc: niwi@… added

I tried to reproduce the bug with this test:

@skipUnless(test_images, "PIL not installed")
def test_model_image_field(self):
    from django.core.files.base import ContentFile
    f = ContentFile(b'not an image')
    with open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb') as fp:
        image_data = fp.read()

    instance = ImageFile()
    instance.image.save("foo.png", SimpleUploadedFile("foo.png", image_data))

    instance2 = ImageFile()
    instance2.image.save("foo.png", f)

And I get is this:

======================================================================
ERROR: test_model_image_field (modeltests.model_forms.tests.OldFormForXTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/niwi/django/tests/modeltests/model_forms/tests.py", line 1250, in test_model_image_field
    instance2.image.save("foo.png", f)
  File "../django/db/models/fields/files.py", line 348, in save
    super(ImageFieldFile, self).save(name, content, save)
  File "../django/db/models/fields/files.py", line 89, in save
    setattr(self.instance, self.field.name, self.name)
  File "../django/db/models/fields/files.py", line 334, in __set__
    self.field.update_dimension_fields(instance, force=True)
  File "../django/db/models/fields/files.py", line 412, in update_dimension_fields
    width = file.width
  File "../django/core/files/images.py", line 15, in _get_width
    return self._get_image_dimensions()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

----------------------------------------------------------------------

comment:2 by Claude Paroz, 14 years ago

Triage Stage: Unreviewed → Accepted

Currently, the verification that the content is an image is done by the ImageField form field (see its to_python method), not in the model field.

Accepted on the base that we should at least:

  • Improve the error message as shown in the previous comment.
  • Clarify the documentation

Validating that the file is really an image file at the model level might be something to evaluate, but with great care, because of the performance issue involved by this operation. Opinions/design decision needed here.

comment:3 by Adam DePrince <deprince@…>, 14 years ago

What constitutes a valid image will depend on how the image is processed --- Imagemagick, netpnm and PIL all disagree slightly on the definition of "an image". We should also consider what it means to "validate" the image --- basic magic number checking will catch the common cases where a user uploads something decidedly not an image, like an mp3 file, but we should stress in our documentation that just because the image passed our "validation" does not mean what was uploaded is actually an image or even safe to process.

What if ImageField accepted anything for which "file -b --mime-type" responds with a match to "$image/" ?

comment:4 by Adam DePrince <deprince@…>, 14 years ago

Cc: deprince@… added

comment:5 by Adam DePrince <deprince@…>, 14 years ago

Owner: changed from nobody to deprince

A quick survey shows that the python options for file seem to be lib magic based. I don't think we really want to see yet another c dependencey in django so I'll spend the rest of my djangocon 2012 sprint time banging out a pure python port.

comment:6 by Mariusz Felisiak, 4 years ago

Owner: deprince removed
Status: new → assigned

comment:7 by Mariusz Felisiak, 4 years ago

Status: assigned → new

comment:8 by Joel Burns, 2 years ago

I would like to work on this, it is my first attempt at a bug fix.
I will need extra time, Im going to replicate the bug, come up with a proposal
and communicate my ideas.

comment:9 by Joel Burns, 2 years ago

Owner: set to Joel Burns
Status: new → assigned

comment:10 by Joel Burns, 2 years ago

Hi, from what I can deduce from the previous comments, In this context, the Django image.field is used to validate the uploaded image file and no other third party libraries. The fix in this case would be to have the error message refer users to the ImageField documentation needing pillow to be installed?

comment:11 by Joel Burns, 2 years ago

Owner: Joel Burns removed
Status: assigned → new

comment:12 by Goodluck Igbokwe, 4 weeks ago

Owner: set to Goodluck Igbokwe
Status: new → assigned

Still reproducible on main (10cd58cf2e).

Minimal reproduction:

from django.db import models
from django.core.files.base import ContentFile

class Item(models.Model):
    image = models.ImageField(upload_to="images/")

item = Item()
item.image.save("fake.jpg", ContentFile(b"not an image"))
item.full_clean()
item.save()

This runs and saves to storage with no errors raised:

>>> item.image.name

'images/fake.jpg'

However, if height_field or width_field is specified on the model:

class ItemWithDims(models.Model):
    image = models.ImageField(
        upload_to="images/",
        height_field="image_height",
        width_field="image_width",
    )
    image_height = models.PositiveIntegerField()
    image_width = models.PositiveIntegerField()

item = ItemWithDims()
item.image.save("fake.jpg", ContentFile(b"not an image"))

It crashes on save() with:

sqlite3.IntegrityError: NOT NULL constraint failed: app_itemwithdims.image_height

Both behaviors stem from models.ImageField in django/db/models/fields/files.py:

  1. models.ImageField defines no default_validators, unlike forms.ImageField which defines default_validators = [validators.validate_image_file_extension]. Furthermore, image validation via Pillow (Image.open().verify()) only exists in forms.ImageField.to_python().
  1. When dimension fields are configured, update_dimension_fields() calls get_image_dimensions(), which returns (None, None) when Pillow fails to parse the file. Dimensions are then set to None, leading to a database IntegrityError if the columns are non-nullable, rather than any image-specific error.

Meanwhile, the documentation states:

“Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.”

Which is not what happens at the model layer.

I’d like to work on this (I'm a fellow in Djangonaut Space ).

comment:13 by Goodluck Igbokwe, 4 weeks ago

Has patch: set

I opened PR #22210 to address the documentation aspect of this ticket. The patch clarifies that models.ImageField itself doesn’t validate whether a saved file contains a valid image.

comment:14 by Johannes Maron, 3 weeks ago

Needs documentation: set
Patch needs improvement: set

Hi there,

Thanks for taking on such an old issue! I believe documenting the current behavior is a good first step. However, I wouldn't necessarily close the ticket. I believe we could potentially emit a warning or log a warning if get_image_dimensions. It's not really EAFP to silently return None,None I believe we would solve this differently today if it were reimplemented.

Cheers!
Joe

comment:15 by Johannes Maron, 3 weeks ago

Needs documentation: unset
Patch needs improvement: unset
Triage Stage: Accepted → Ready for checkin

comment:16 by Sarah Boyce, 3 weeks ago

Patch needs improvement: set
Triage Stage: Ready for checkin → Accepted

comment:17 by Goodluck Igbokwe, 3 weeks ago

Patch needs improvement: unset

comment:18 by Sarah Boyce, 3 weeks ago

Triage Stage: Accepted → Ready for checkin

comment:19 by Sarah Boyce <42296566+sarahboyce@…>, 2 weeks ago

Resolution: → fixed
Status: assigned → closed

In 6a8248f:

Fixed #18543 -- Corrected ImageField validation documentation.

comment:20 by Sarah Boyce <42296566+sarahboyce@…>, 2 weeks ago

In 11bb658:

[6.1.x] Fixed #18543 -- Corrected ImageField validation documentation.

Backport of 6a8248f13fe7b51c4414eeaf3554a666464b2636 from main.

Note: See TracTickets for help on using tickets.
Back to Top