0

Trying to upload an image to a model image field with AJAX. Here's my code:

js

$('input#id_banner_image').on('change', function(e) {

    $.ajax({
        type: 'POST',
        url: '/change_banner_image/',
        data: {
            image: URL.createObjectURL(e.target.files[0]),
            csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()
        }

    })
});

views

def change_banner_image(request):
    if request.is_ajax():
        print(request.FILES) #prints <MultiValueDict: {}>
        for i in request.FILES:
            print(i) #prints nothing
        image = request.FILES['id_banner_image'].name #this is wrong
        profile = get_object_or_404(Profile, user=request.user)
        profile.image = image
        profile.save()

    return HttpResponse()

How do I correctly grab the image in my views? I know that's the bit that's wrong.

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • Have you checked that `request.FILES['id_banner_image']` contains the data for the image? Also, is `profile.image` a `model.ImageField` or similar as you'll need to make sure the image data is saved to a file etc... – Jon Clements Sep 16 '17 at 08:25
  • Yes I've checked that, if i remove the `.name` then I get this error: `django.utils.datastructures.MultiValueDictKeyError: "'id_banner_image'"`. `profile.image` is a `models.FileField` – Zorgan Sep 16 '17 at 08:27
  • 1
    then you need to work on making sure your request includes the necessary stuff in `request.FILES`... so print that out and see what it's got, then tweak the front-end until you can access it... – Jon Clements Sep 16 '17 at 08:29
  • Possible duplicate of [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – markwalker_ Sep 16 '17 at 08:48
  • @JonClements can you tell me what I should print to see the contents of `request.FILES`? If you look in my edit, i've tried to access it but it returns no useful information. I know there's no problem with the front-end because I can successfully see the picture come up in my AJAX `success` function. – Zorgan Sep 16 '17 at 09:27
  • Could you please add your rendered form and the javascript containing the ajax request please? – Pablo Vergés Sep 16 '17 at 13:51

0 Answers0