From 6429d71ecbfd778d56ede1a51224286c81eab7f6 Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Tue, 22 Oct 2019 23:18:21 +0200 Subject: [PATCH] [2.2.x] Fixed #30252 -- Clarified need to reopen forms.fields.ImageField.image file to access raw image data. Backport of 2282d9f2e5d08fc782087ebe97ab195303a6e79b from master --- docs/ref/forms/fields.txt | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index 10bcc0eb3a..6f76d0d6ed 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -710,9 +710,41 @@ For each field, we describe the default widget used if you don't specify After the field has been cleaned and validated, the ``UploadedFile`` object will have an additional ``image`` attribute containing the Pillow - `Image`_ instance used to check if the file was a valid image. Also, - ``UploadedFile.content_type`` will be updated with the image's content type - if Pillow can determine it, otherwise it will be set to ``None``. + `Image`_ instance used to check if the file was a valid image. Pillow + closes the underlying file descriptor after verifying an image, so whilst + non-image data attributes, such as ``format``, ``height``, and ``width``, + are available, methods that access the underlying image data, such as + ``getdata()`` or ``getpixel()``, cannot be used without reopening the file. + For example:: + + >>> from PIL import Image + >>> from django import forms + >>> from django.core.files.uploadedfile import SimpleUploadedFile + >>> class ImageForm(forms.Form): + ... img = forms.ImageField() + >>> file_data = {'img': SimpleUploadedFile('test.png', )} + >>> form = ImageForm({}, file_data) + # Pillow closes the underlying file descriptor. + >>> form.is_valid() + True + >>> image_field = form.cleaned_data['img'] + >>> image_field.image + + >>> image_field.image.width + 191 + >>> image_field.image.height + 287 + >>> image_field.image.format + 'PNG' + >>> image_field.image.getdata() + # Raises AttributeError: 'NoneType' object has no attribute 'seek'. + >>> image = Image.open(image_field) + >>> image.getdata() + + + Additionally, ``UploadedFile.content_type`` will be updated with the + image's content type if Pillow can determine it, otherwise it will be set + to ``None``. .. _Pillow: https://pillow.readthedocs.io/en/latest/ .. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html