How do I open an image from an ImageField before validating and saving a form?

advertisements

I want to get the value of a CharField based on the value of an ImageField. My form and view are defined as:

#Form
class GpsImForm(forms.Form):
    image = forms.ImageField(required=True)
    gps_data = forms.CharField(required=True)

#View
def gpsim_gen_view(request):
    if request.method == 'POST':
        form = GpsImForm(request.POST, request.FILES)
        if 'image' in request.FILES:
            im = request.FILES['image']
            i = Image.open(im)
            ... # functions to extract exif data from i
            request.POST.update({ 'gps_data': ...}) # set gps_data based on exif data from i
        if form.is_valid():
            obj = form.save()
            return ... #returns the gpsim
    else:
        form = GpsImForm()
    return direct_to_template(request, 'gpsim_generate.html', {'form': form,})

The gps_data is updated, but, as soon as I use Image.open(), I get the following error message:

Upload a valid image. The file you uploaded was either not an image or a corrupted image.

If I comment the lines concerning i and modify the gps_data to whatever, the form (with the image) is saved without any error...

# i = Image.open(im)
# ...
# functions to extract exif data from i
request.POST.update({ 'gps_data': 'some text'}) # set gps_data to 'test'


first of all, make sure that your form has the enctype tag

<form enctype="multipart/form-data" ... >

Try to write the img (all the chunks) on disk:

import Image
from random import choice
from django.conf import settings

random_file_name = getattr(settings, 'FILE_UPLOAD_TEMP_DIR', '/tmp')
random_file_name +=  '/' + ''.join([choice('abcdefg') for i in range(12)]) + '.jpg'

destination = open(random_file_name, 'wb+')
for chunk in request.FILES['image'].chunks():
    destination.write(chunk)
destination.close()

Then, you can open it from disk:

image = Image.open(random_file_name)
if image.mode != "RGB":
    image = image.convert("RGB")

...

This URL may help you:

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/