1

Few days before i learned that we can make file uploads with ajax. So i tried to build an app that uploads selected file when other parts of form being filled by user.

my app has two models:

class Post(models.Model):
    image = models.ImageField(...)
    title = ...
    desc = ...

class TempImg(models.Model):
    image = models.ImageField(...)
    posted_by = ...
    posted_at = ...

That form used to make a post, here you can see temp_image as hidden input:

class PostForm(forms.ModelForm):
    temp_image = forms.IntegerField(widget=forms.HiddenInput)
    class Meta:
        model = Post

When user selects image, this javascript code uploads it and puts returning id value to temp_image field of form:

// here is a function that gets csrftoken, [which is taken from docs
// https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

csrftoken = ...

form = new FormData();
form.append("image", dataURLToBlob(resizedImgData));
form.append("csrftoken", csrftoken)

$.ajax({
    url: '/upload/',
    data: form,
    processData: false,
    contentType: false,
    dataType: 'json',
    type: 'POST',
    beforeSend: function() {
        $("#uploadingIndicator").show()
    },
    success: function(data){
        $("#id_temp_image").val(data['id'])
        $("#uploadingIndicator").hide();
    }
});

Everything seems OK to me but, there is a problem that my view always return 403. CSRF verification error.

Can anybody have an idea where should i look at? I am going to use csrf_exemt if i can not find solution...

1

1 Answer 1

2

You should use

form.append("csrfmiddlewaretoken", csrftoken)

While you were trying to do form.append("csrftoken", csrftoken)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.