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.
Written by Snir David
Related protips
14 Responses
Thanks. I wish Django had a multi-file uploader built into Admin though. :(
where is your next post ?
You somewhat saved my life, how do you actually view the image??
Thanks, very helpful!
What is "pk=course_id"?
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 :(
Hi. Is it possible to do it without using form? eg. use ajax post method ? $('.photo input').val()?
Thanks, very informative and helpful
Thanks a lot!
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
Thank you so much!!!
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
Thanks man o/
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