2

Redirect in Django is not working when files are uploaded using Dropzone.js, so I used windows.href in the Dropzone success event but I have to pass a parameter.

views.py:

if request.method == 'POST' and request.FILES['files']:
    ...
    if form.is_valid():
        ....
        user = User.objects.get(email=email)
        id = user.id
        return redirect(reverse('success', kwargs={'id': id})) <<-- not working 

JQuery - Dropzone:

this.on('success', function() {
    window.location.href = '/success/';
})

I don't reckon there is a way to pass the id to JQuery in this case, so I have to use redirect in Django. How can it get done?

Ahtisham
  • 9,170
  • 4
  • 43
  • 57
elle
  • 103
  • 1
  • 1
  • 8

1 Answers1

1

The reason why django redirect is not working is because dropzone.js uses AJAX for its post requests which doesn't redirect pages.

To get the redirect to work you need to get the dropzone to redirect with javascript to the correct url given as a response from the POST request. The view returns a JSON response that then can be parsed from the js. This is done as follows:

from django.http import JsonResponse

def index(request):

    if request.method == 'POST':
        form = BenchmarkForm(request.POST, request.FILES)
        if form.is_valid():

            model_id = YourModel.objects.create(file=request.FILES['file']).id

            link = reverse('energy:benchmark',kwargs={'id':model_id})

            response = {'url':link} 

            return JsonResponse(response)

Then in the dropzone init function you need to parse the response in the success callback.

 Dropzone.options.myDropzone = {

                // Prevents Dropzone from uploading dropped files immediately
                autoProcessQueue : false,
                url: "{% url 'energy:index' %}",

                headers: {
                     "X-CSRFToken": "{{ csrf_token }}"
                },

                init : function() {
                    mydropzone = this;

                    this.on("success", function(file, response) {
                        window.location.href=JSON.parse(file.xhr.response).url
                    });
kyczawon
  • 455
  • 6
  • 14