bz0sng
Last Updated: September 09, 2019
·
181.5K
· 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 %}
    <p>
        <input id="id_image" type="file" class="" name="image">
    </p>
    <input type="submit" value="Submit" />
</form>

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']
            m.save()
            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

2611

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

over 1 year ago ·
9369

where is your next post ?

over 1 year ago ·
9916

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

over 1 year ago ·
10984

Thanks, very helpful!

over 1 year ago ·
11083

What is "pk=course_id"?

over 1 year ago ·
12875

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 ·
15424

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

over 1 year ago ·
15661

Thanks, very informative and helpful

over 1 year ago ·
16749

Thanks a lot!

over 1 year ago ·
17609

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 ·
22034

Thank you so much!!!

over 1 year ago ·
24908

How you can send the file and the json using

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

upload_result = self.client.post("/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 ·
26252

Thanks man o/

over 1 year ago ·
26254

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 ·