Home > programming > Fix for JPEG upload problem in Django in virtualenv

Fix for JPEG upload problem in Django in virtualenv

December 2nd, 2009

I have been busy modifying Django’s models for a project to include a field for uploading an image and was testing the model using Django’s Admin interface when I suddenly got this error:

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


Here’s a screenshot (click on it for a larger view):

django-upload-jpeg-problem

This has worked before so I was stumped to find out it’s giving me a red flag now.

Django is using Python Imaging Library or PIL for images so understandably the culprit may be on this level.  I tested PIL in Python’s shell using these commands:

$ python
>>> from PIL import Image
>>> img = Image.open("/home/cyril/Pictures/Anatomy.jpg")
>>> img.verify()
>>> img.size
(1600,1200)

Clearly, nothing is wrong with my PIL installation.

I began searching the net and found the following fix: Fixing – PIL IOError: decoder jpeg not available. Obviously, the author’s problems are similar to mine but he wasn’t using Django, only Python.

Since I have been using virtualenv to sandbox my Django projects, I have a similar but different approach.

Here are the steps I took to fix this problem:

  1. I removed PIL by deleting the PIL folder and the PIL.pth file from my project’s virtualenv path.
  2. I then installed the JPEG library using:
    $ sudo aptitude install libjpeg libjpeg-dev
  3. I then re-installed PIL on my project using:
    $ pip install -E ../projectname/ -r requirements.txt

After this, I have successfully uploaded a .jpg file in Django’s admin interface.

This fix is useful if you are using virtualenv to sandbox your Django projects like me.  Here is my post on how to do this.  If you are not using virtualenv, just do the above steps but re-install PIL as you normally do using easy_install or pip.

A note of advice when installing PIL.  Read the PIL Setup Summary displayed after the installation.

This PIL Setup Summary says there is No JPEG support (click on it for a larger view):

pil-install-without-jpeg-library-1While this PIL Setup Summary says there is JPEG support (click on it for a larger view):

pil-install-with-jpeg-library-1

I must have missed that during my virtualenv installation which caused me hours of gasping agony (as if being constricted by a python). :D

Thankfully I found the fix.  Kudos to Greg Pinero for posting it.

Happy Coding!

List of related articles on myListBoard.com:

Author: Cyril Pauya Categories: programming Tags: , , , , ,
  1. Chris
    March 8th, 2010 at 07:12 | #1

    This was driving me bonkers. Thanks for posting.

  2. March 14th, 2010 at 03:34 | #2

    @Chris
    Glad to be of help. :)

  3. June 27th, 2010 at 01:26 | #3

    thanks! this what i am looking for. great job.

  1. No trackbacks yet.