How to save an image using django imageField?

Yogev Shelly picture Yogev Shelly · Jan 11, 2012 · Viewed 19.7k times · Source

posting from an app (iOS android etc..) not a web form.

class someImage(models.Model):
    image = models.ImageField(upload_to= settings.SHARE_IMAGE_UPLOAD_PATH)

@csrf_exempt
def saveImage(request):

How to write the view? it receives an image in a post request. Every thing i find is form related (server newbie)

Answer

Chris Pratt picture Chris Pratt · Jan 11, 2012

Just because you're not using an actual HTML form to submit the data doesn't mean you can't use a ModelForm to process the request:

from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.utils import simplejson

def upload_view(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            result = {'success': True}
            return HttpResponse(simplejson.dumps(result), mimetype='application/json')
        else:
            return HttpResponseBadRequest()
    else:
       return HttpResponseNotAllowed(['POST'])