bz0sng
Last Updated: April 07, 2016
·
104.3K
· snird
578515 10151152562191590 343240775 n

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.

Say Thanks
Respond

14 Responses
Add your response

2611
Cory simmons 700

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

over 1 year ago ·
9369
B923c7e8b8c39468e6395eafd81d92cd

where is your next post ?

over 1 year ago ·
9916
A351f6d1992deb61fab3c12f88f5c0c3

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

over 1 year ago ·
10984
C1428d36c91a53a1e4c39fb2c7ceff15

Thanks, very helpful!

over 1 year ago ·
11083
A1c5492dbdac472693716714cfbe5d24

What is "pk=course_id"?

over 1 year ago ·
12875
7ccb22084b6cf6944b15d43c4f492e85

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
Photo0421 normal

Thanks, very informative and helpful

over 1 year ago ·
16749
No photo

Thanks a lot!

over 1 year ago ·
17609
None

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
None

Thank you so much!!!

over 1 year ago ·
24908
None

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
4123fa0be86f5b0eb7fe2795888b3002

Thanks man o/

over 1 year ago ·
26254
0  76t6qpzkymthhtwlmotiivzlizthraqzokt8ttzzjohhhiojoy1mnvz s0tht wj7yteimvjsz8 qmfgpimatqmysz3 qbqgpillp3nbuhswgyvasv05ff5pffaoqrbqxbycs47avp

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 ·