Last Updated: September 09, 2019
· snird

Simple Django Image upload to model imagefield

This is a simple snippet to make an image upload to your model in django.
Assuming you need only the image field, making a modelform is futile, so instead I make a most simple form class:

class ImageUploadForm(forms.Form):
    """Image upload form."""
    image = forms.ImageField()

and my example of Model:

class ExampleModel(models.Model):
    model_pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/no-img.jpg')

Given those, the html form within the template should be something like that:

<form action="{% url upload_pic %}" method="post" enctype="multipart/form-data">{% csrf_token %}
        <input id="id_image" type="file" class="" name="image">
    <input type="submit" value="Submit" />

What is important to notice here is that the form has "enctype" of enctype="multipart/form-data" which is necessary for the file upload.

The view might look like that: (my view does not serve any template, since my implementation is via Ajax, on that in my next post

def upload_pic(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            m = ExampleModel.objects.get(pk=course_id)
            m.model_pic = form.cleaned_data['image']
            return HttpResponse('image upload success')
    return HttpResponseForbidden('allowed only via POST')

here again, one of the common pitfalls is forgetting about the "request.FILES" which most be given to the form class initializer when dealing with files.

have fun.

14 Responses
Add your response


Thanks. I wish Django had a multi-file uploader built into Admin though. :(

over 1 year ago ·

where is your next post ?

over 1 year ago ·

You somewhat saved my life, how do you actually view the image??

over 1 year ago ·

Thanks, very helpful!

over 1 year ago ·

What is "pk=course_id"?

over 1 year ago ·

pk := primary key (generally the ID column of your table)

another question: here you use a model for uploading. But what if I don't want to use a model? The model gives you an easy upload_to= that the forms module doesn't give you :(

over 1 year ago ·

Hi. Is it possible to do it without using form? eg. use ajax post method ? $('.photo input').val()?

over 1 year ago ·

Thanks, very informative and helpful

over 1 year ago ·

Thanks a lot!

over 1 year ago ·

excuse me,,I follow your code, but it tells me:global name 'course_id' is not defined,,,can you teach me why? thanks very much

over 1 year ago ·

Thank you so much!!!

over 1 year ago ·

How you can send the file and the json using

headers = {'content-type': 'multipart/form-data'}
image = open('img.jpg', 'rb')
payload = {'id':} 
files = {'photo': image}    

upload_result ="/image/", data=payload, files=files, headers=headers)
print upload_result
print upload_result.content

The issue is request.FILES on the server side is NONE. How to handle this ? I am using locust load testing tool

over 1 year ago ·

Thanks man o/

over 1 year ago ·

hello Sir
how can i convert the image uploaded in the above given code to gray scale and will you please guide me when form.cleaned_data['image'] have got data from client what type of data is it? is it unicode? or if is it unicode how can i convert this into gray scale image
kindly help me i'll be very thank ful to you

over 1 year ago ·