Django (AJAX post request)

Hey there!

I want the client to be able to crop images stored in the app server (I use Cropperjs to crop the image, AJAX to send the post with the cropped image). Once the client crop the image, the server receives it and is used for further processing. So far I have this:

View

from .models import Image

def main_view(request):
    
    obj = Image.objects.get(pk=1)
    context = {'obj':obj}
    return render(request, 'main.html',context)

template + Cropperjs logic

<img src="{{obj.file.url}}" id="image" width="400px" >
{% csrf_token %}
<input type="button" id="confirm-btn" value="Start cropping" />

<script>
(Section for cropping the image)

$.ajax('media/images/', {
            method: 'POST',
            enctype: 'multipart/form-data',
            data: formData,
            processData: false,
            contentType: false,
            success() {
              console.log('Upload success');
            },
            error() {
              console.log('Upload error');
            },
          });
        });

</script>

I am receiving the error : Forbidden (CSRF token missing or incorrect.): /media/images/ for the post.
I have done this with a form and it works (when client uploads their image). However in this case they are editing images stored in the server. Someone to shed light on this matter?

Thanks!

It seems you’re forgetting to send the csrf token with the AJAX request.
You can grab it from the DOM with JS.

<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
</script>

https://docs.djangoproject.com/en/3.2/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true

Yes, now I’m receiving the post request.

Thank you!

1 Like