0

I am trying to upload an image via AJAX with a Django view. Here is my HTML form.

<form class="BackgroundImageUplaoder" action="/uplaod" id="form2">{% csrf_token %}
<input type="file" accept="/image*" name="image" multiple="false" />
<button type="submit">Uplaod</button>

While the corresponding ajax is:-

$(document).ready(function(){
$('#form2').submit(function(){
    var csrftoken = $("[name=csrfmiddlewaretoken]").val();

    var formdata={
        'image':$('input[name=image]').val(),

    };
    console.log("Formvalue is taken");
    console.log(formdata.image);

    $.ajax({
        type:'POST',
        url:'/Upload/Background/',
        data:formdata,
        dataType:'json',
        encode:true,
        headers:{
        "X-CSRFToken": csrftoken
        },
        processData:false,
        contentType:false,
    })

    .done(function(data){
        console.log(data);
        if(!data.success){//we will handle error
            if (data.password){
                console.log(data.password);
                    $('#password_error').text(data.password);
            }
            return false;

        }
            else{
                window.location='/';
            }

    });
event.preventDefault();
});
 });

and django view is:-

def uploadbackground(request):
if request.method=="POST":
    form=BackgroundImageUplaod(request.POST,request.FILES)
    if form.is_valid():
        instance=form.save(commit=False)
        myobject=HomeScreen.objects.get(profile__user=request.user)
        if myobject:
            myobject.image=instance
            myobject.save()
            return JsonResponse({'success':True})
        else:
            sample=HomeScreen(profile__user=request.user,image=instance)
            sample.save()
            return JsonResponse({'success':True})
else:
    form=BackgroundImageUplaod()
return JsonResponse({'image':'An error is encountered while uplaoding','errors': [(k, v[0]) for k, v in form.errors.items()]})

The console is showing following errorenter image description here

According to my view, The form is not validating.After validating my forming. I am checking that whether the instance correponding to current logged in user exist or not.If yes i am updating that instance otherwise creating new object

1 Answer 1

1

Your issue is that you cannot send an image via an AJAX JSON POST, which only accepts strings and integers. You need to use formData.

https://webkul.com/blog/send-images-through-ajax/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.