How do i include the csrf_token to dropzone Post request (Django)
<p>Allright this is resolved. Just editing in case anyone runs into the same problem.</p>

<p>Add the Code posted in Comment marked as answer in the same javascript file.
When defining</p>

<pre><code>var myDropzone =  new Dropzone(...
  ...//More stuff here
  headers:{
    'X-CSRFToken' : csrftoken
  }
</code></pre>

<p>And thats it.</p>

<p>So im getting a 403 Forbidden when submitting the POST request through dropzone.js to django.Django displayed the message saying that I didnt include the CSRF token, but I don't know how to actually include it if im not using a form in the HTML.</p>

<h1>document_form.html</h1>

<pre><code>{% extends 'base.html'  %}
{% load staticfiles %}
{% block title %}Add files{% endblock %}
{% block files %}
&lt;div class="container-fluid" id="container-dropzone"&gt;
&lt;div id="actions" class="row"&gt;

  &lt;div class="col-lg-7"&gt;
    &lt;span class="btn btn-success file-input-button"&gt;
      &lt;i class="glyphicon glyphicon-plus"&gt;&lt;/i&gt;
      &lt;span&gt;Add files...&lt;/span&gt;
    &lt;/span&gt;
    &lt;button type="submit" class="btn btn-primary start"&gt;
      &lt;i class="glyphicon glyphicon-upload"&gt;&lt;/i&gt;
      &lt;span&gt;Start upload&lt;/span&gt;
    &lt;/button&gt;
    &lt;button type="reset" class="btn btn-warning cancel"&gt;
      &lt;i class="glyphicon glyphicon-ban-circle"&gt;&lt;/i&gt;
      &lt;span&gt;Cancel upload&lt;/span&gt;
    &lt;/button&gt;
  &lt;/div&gt;

  &lt;div class="col-lg-5"&gt;
  &lt;!-- file processing state --&gt;
    &lt;span class="fileupload-process"&gt;
      &lt;div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"&gt;
        &lt;div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/span&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;div class="table table-striped files" id="previews"&gt;
  &lt;div id="template" class="file-row"&gt;
    &lt;div&gt;
      &lt;span class="preview"&gt;&lt;img data-dz-thumbnail&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;p class="name" data-dz-name&gt;&lt;/p&gt;
      &lt;strong class="error text-danger" data-dz-errormessage&gt;&lt;/strong&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;p class="size" data-dz-size&gt;&lt;/p&gt;
      &lt;div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
                 aria-valuemax="100" aria-valuenow="0"&gt;
        &lt;div class="progress-bar progress-bar-success" style="width:0%" 
                    data-dz-uploadprogress&gt;
        &lt;/div&gt;           
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;button class="btn btn-primary start"&gt;
        &lt;i class="glyphicon glyphicon-upload"&gt;&lt;/i&gt;
        &lt;span&gt;Start&lt;/span&gt;
      &lt;/button&gt;
      &lt;button data-dz-remove class="btn btn-warning cancel"&gt;
        &lt;i class="glyphicon glyphicon-ban-circle"&gt;&lt;/i&gt;
        &lt;span&gt;Cancel&lt;/span&gt;
      &lt;/button&gt;
      &lt;button data-dz-remove class="btn btn-danger delete"&gt;
        &lt;i class="glyphicon glyphicon-trash"&gt;&lt;/i&gt;
        &lt;span&gt;Delete&lt;/span&gt;
      &lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt; &lt;!-- /table-striped  --&gt;
&lt;/div&gt; &lt;!-- /container-fluid  --&gt;
&lt;/div&gt;
{% endblock %}
{% block dz-add %}
  &lt;script src="{% static 'js/dropzone-bootstrap.js' %}"&gt;&lt;/script&gt;
{% endblock %}
</code></pre>

<h1>dropzone-bootstrap.js</h1>

<pre><code>$(function() {
  var previewNode = document.querySelector("#template");
  previewNode.id = "";
  var previewTemplate = previewNode.parentNode.innerHTML;
  previewNode.parentNode.removeChild(previewNode);

  var myDropzone = new Dropzone(document.querySelector("#container-dropzone") , {
    url: "/dashby/files/add/", //url to make the request to.
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    parallelUploads: 20,
    previewTemplate: previewTemplate,
    autoQueue: false,
    previewsContainer: "#previews",
    clickable: ".file-input-button",
    headers: { // Tried to apply the token this way but no success.
      'X-CSRFToken': $('meta[name="token"]').attr('content')
    }
  });

  myDropzone.on("addedfile", function(file){
    file.previewElement.querySelector(".start").onclick = function(){
      myDropzone.enqueueFile(file);
      };
  });

  myDropzone.on("totaluploadprogress", function(progress){
    document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
  });

  myDropzone.on("sending", function(file){
    // Show total progress on start and disable START button.
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
  });

  // Hide progress bar when complete.
  myDropzone.on("queuecomplete", function(progress){
    document.querySelector("#total-progress").style.opacity = "0";
  });

  // Setup buttons for every file.
  document.querySelector("#actions .start").onclick = function(){
    myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
  };
  document.querySelector("#actions .cancel").onclick = function(){
    myDropzone.removeAllFiles(true);
  };
});
</code></pre>

<p>In my <strong>base.html</strong> im adding all the required files (dropzone, jquery, bootstrap and my custom javascript file)</p>

<p>For the django form handling:</p>

<h1>views.py</h1>

<pre><code>class DocumentCreate(CreateView):
    model = Document
    fields = ['file']
    def form_valid(self, form):
        self.object = form.save()
        data = {'status': 'success'}
        response = JSONResponse(data, mimetype =
        response_mimetype(self.request))
        return response
</code></pre>

<h1>My "Document" model</h1>

<pre><code>class Document(models.Model):
    file = models.FileField(upload_to = 'files/',
                                validators=[validate_file_type])
    uploaded_at = models.DateTimeField(auto_now_add = True)
    extension = models.CharField(max_length = 30, blank = True)
    thumbnail = models.ImageField(blank = True, null = True)

    def clean(self):
        self.file.seek(0)
        self.extension = self.file.name.split('/')[-1].split('.')[-1]
        if self.extension == 'xlsx' or self.extension == 'xls':
            self.thumbnail = 'xlsx.png'
        elif self.extension == 'pptx' or self.extension == 'ppt':
            self.thumbnail = 'pptx.png'
        elif self.extension == 'docx' or self.extension == 'doc':
            self.thumbnail = 'docx.png'

    def delete(self, *args, **kwargs):
        #delete file from /media/files
        self.file.delete(save = False)
        #call parent delete method.
        super().delete(*args, **kwargs)

    #Redirect to file list page.
    def get_absolute_url(self):
        return reverse('dashby-files:files')

    def __str__(self):
        #cut the 'files/'
        return self.file.name.split('/')[-1]

    class Meta():
        #order by upload_date descending
        #for bootstrap grid system. (start left side)
        ordering = ['-uploaded_at']
</code></pre>

<p>I created a Json response to handle the dropzone.</p>

<h1>response.py</h1>

<pre><code>from django.http import HttpResponse
import json

MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'

# Integrating Dropzone.js with Django.
def response_mimetype(request):
    can_json = MIMEJSON in request.META['HTTP_ACCEPT']
    can_json |= MIMEANY in request.META['HTTP_ACCEPT']
    return MIMEJSON if can_json else MIMETEXT

# Custom HttpResponse
class JSONResponse(HttpResponse):
    def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON,
                *args, **kwargs):
        json_opts = json_opts if isinstance(json_opts, dict) else {}
        content = json.dumps(obj, **json_opts)
        super(JSONResponse, self).__init__(content, mimetype,
                                          *args, **kwargs)
</code></pre>

<p>I've been stuck with this problem for a day now, so decided to ask for help here as I havn't been able to find one.</p>

<p>Thanks to anyone that takes the time to read and for any help/tips that I can get.</p>

<p>The <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax" rel="nofollow">docs</a> recommend getting the CSRF token from the cookie, not the DOM. Try that.</p>

javascript jquery python django dropzone.js