Django重定向无法与dropzone.js一起工作

问题描述 投票:0回答:1

当使用Django上传文件时,Django中的重定向不工作。Dropzone.js,所以我用 windows.href 在坠落区 success 事件,但我必须传递一个参数。

视图.py.Views.JQuery

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/';
})

我不认为有一个方法来传递事件中的 id 到JQuery,所以我必须在Django中使用重定向。如何才能做到呢?

django redirect dropzone
1个回答
0
投票

django重定向不能工作的原因是dropzone.js使用AJAX的post请求,而AJAX请求并不重定向页面。

为了让重定向工作,你需要让dropzone用javascript重定向到作为POST请求响应的正确url。视图会返回一个JSON响应,然后可以从js中进行解析。具体操作如下。

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)

然后在dropzone初始函数中,你需要在成功回调中解析响应。

 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
                    });
© www.soinside.com 2019 - 2024. All rights reserved.