Home > Net >  CSRF Token problem when I add dropzone to an existing form in Django
CSRF Token problem when I add dropzone to an existing form in Django

Time:10-14

I'm working with a Django form using dropzone to upload images. But I don't want to add the dropzone to the entire form, just to a div of it. Here is the template:

{% extends 'base.html' %}
{% load static %}
{% load i18n %}
{% block content %}
<h6>UPLOAD MULTIPLE IMAGES NOW</h6>
<br>
<div class="formdiv" style="width:100%">
<form enctype="multipart/form-data" action="upload/" methd="POST">
    {% csrf_token %}
    <fieldset>
        <label for="yourname">Yourname
            <input type="text" value="name" />
        </label>
        <div class="dropzone dz" id="my-dropzone">
            <div class="dz-message" data-dz-message><span>{% trans "Drop here or click to upload" %}</span></div>
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
        </div>
    </fieldset>
</form>
</div>
{% endblock %}

The problem is that when I try to upload any image I get a Forbidden error message with the following text:

CSRF token missing or incorrect.

Notice that if I remove the class="dropzone dz" id="my-dropzone" from the div and I put it inside the <form> tag instead, everything will work. The problem began exactly when I moved dropzone in a div because I didn't want it to apply to the whole form.

Here is my dropzone configuration code:

Dropzone.autoDiscover=false;
const myDropzone = new Dropzone('#my-dropzone',{
    url:'upload/',
    maxFiles:15,
    maxFilesize:5, // 5 mb max
    //parallelUploads:2,
    // if image is horizontal, then resize it if it's more than resizeWidth
    resizeWidth:1024,
    // if the image is vertical, then resize if it's more than resizeHeight
    resizeHeight:1024,
    // also they can be mime such as image/png
    acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.webp",
    // default is false and it allows to delete uploaded files
    addRemoveLinks: true,
    // this is the element where the remove button or text will be located
    dictRemoveFile: "<div><span class='fa fa-trash text-danger' style='font-size: 1.5em;cursor:pointer'></span></div>",
 
    /* the following solution failed
    headers: {
        'X-CSRFToken': $('meta[name="token"]').attr('content')
    } */
});

What I have to do to solve this issue?

CodePudding user response:

Looking at the django docs I see it being called X-CSRFToken not X-CSRF-TOKEN. Try fixing that and uncommenting your header code.

The code I see in the docs for getting the token is document.querySelector('[name=csrfmiddlewaretoken]').value try replacing yours with that. Just be sure you have {% csrf_token %} in your page somewhere.

  • Related