Django: Saving an Image using ImageField, Explained a Little


Took me forever to learn how to save an image using ImageField.  Turns out it's crazy easy -- once you know how to do it, it is, at least.  I mean, it all comes together sensibly after you see it.

So basically, you're working with a FileField.  I already looked into the differences between ImageField and FileField:

  • ImageField takes everything FileField takes in terms of attributes, but ImageField also takes a width and height attribute if indicated.
  • ImageField, unlike FileField, validates an upload, making sure it's an image.

Using ImageField comes down to most of the same constructs as FileField does.  The biggest things to remember:


So a form is generated from something in (or wherever your forms are) like this:

imgfile         =   forms.ImageField(label = 'Choose your image',  
                                          help_text = 'The image should be cool.')

In the model, you might have this in correspondence:

imgfile =   models.ImageField(upload_to='images/%m/%d')

So there will be a POST request from the user (when the user completes the form).  That request will contain basically a dictionary of data.  The dictionary holds the submitted files.  To focus the request on the file from the field (in our case, an ImageField), you would use:


You would use that when you construct the model object (instantiating your model class):

newPic = ImageModel(imgfile = request.FILES['imgfile'])

To save that the simple way, you'd just use the save() method bestowed upon your object (because Django is that awesome):

        if form.is_valid():  
            newPic = Pic(imgfile = request.FILES['imgfile'])

Your image will be stored, by default, to the directory you indicate for MEDIA_ROOT in

The tough part, which isn't really so tough when you catch on, is accessing the image.

In your template, you could have something like this:

<img src="{{ MEDIA_URL }}{{ }}"></img>

Where {{ MEDIA_URL }} is something like /media/, as indicated in and {{ }} is the name of the file and the subdirectory you indicated in the model.  "image" in this case is just the current image in a loop of images you might create to access each image in the database:

            {% for image in images %}  
                <li><img src="{{ MEDIA_URL }}{{ }}"></img></li>
            {% endfor %}

Make SURE you configure your urls properly to handle the image or the image won't work.  Add this to your urls:

urlpatterns += patterns('',  
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,

You're serving static files.  An explanation of that can be found here.

Took me a lot of searching.  The Django guys should really make their documentation more comprehensive for learners.  Seriously.

DjFaceChop is almost done!

Til next time!


Software Engineer

Subscribe to GregBlogs