【问题标题】:Stop page from redirecting after form submission in Django在Django中提交表单后停止页面重定向
【发布时间】:2018-02-28 20:30:30
【问题描述】:

我正在使用 django,我创建了一个应用程序,我想在其中上传一个保存在特定位置的 zip 文件(此时我的 django 服务器是 localhost) 我有以下工作正常的代码:

这是我的 HTML 模板:

<form id="saveZipFile" enctype="multipart/form-data" action="" method="post">
    {% csrf_token %}
    <input type="file" name="docfile" id="docfile">
    <input type="submit" id="upload-button" value="Upload">
</form>

这是我的forms.py:

class UploadFileForm(forms.Form):
    docfile = forms.FileField()

这是我的views.py:

def handle_uploaded_file(f):
    with open('uploaded_zip.zip', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)


def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['docfile'])
            return HttpResponse()
    else:
        form = UploadFileForm()
        return HttpResponse()

urls.py:

urlpatterns = [
    url(r'^upload_file/$', views.upload_file, name='upload_file'),
]

但最后,网址更改为 /upload_file - 据我了解,这是正确的 - 并且该页面是空的(因为我返回的是空的 HttpResponse)

我正在尝试构建一个单页应用程序,并且此重定向将我的网页的整个状态抛出窗口。

有什么方法可以让我进行 AJAX 调用而不是使用 django 表单?

谢谢!

编辑

我确实添加了一个 ajax 调用来获取上传的文件并将其发送到 django 视图。

AJAX 调用:

var selectedFile = $('#docfile').files[0];

var fd = new FormData();
fd.append("file", selectedFile);
$.ajax({method: 'POST', 
        url: 'upload_file',
        data: fd, 
        headers: {'Content-Type': undefined, 
                  'X-CSRFToken': getCookie('csrftoken')
        },
        cache: false, 
        processData: false})
        .done(function(data) {
            alert(data)
        });

但是在我打印出request.POST 时的视图中,我得到了这个混乱(以及很多很多行):

<QueryDict: {u'\x00\x00userapp/.git/objects/0e/34e20fc7131238973f102fe6d2d7fe102d12f4UT\x05\x00\x03\ufffd': [u'\xc0Yux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00PK\x01\x02\x1e\x03\n\x00\x00\x00\x00\x001\x852K\x00\x00\x00\x00\x00\x00\

【问题讨论】:

    标签: python ajax django python-2.7 django-forms


    【解决方案1】:

    您应该为此使用 ajax,从表单中检索数据,发出请求并返回 false,这样可以防止发生重定向。它应该是这样的:

    $(function() {
        $('form').submit(function() {
            $.ajax({
                type: 'POST',
                url: 'form-submit.php',
                data: { name: $(this).name.value, 
                        surname: $(this).surname.value }
            });
            return false;
        }); 
    })
    

    【讨论】:

    • 嗯,是的。但我也必须保存 zip 文件的内容,对吗?当我发送 zip 文件内容时,我得到了充满二进制数据的 QueryDict - 我不知道该怎么做。
    • 我调查了一下,当我们使用 django-forms 上传文件时——上传的文件变成了 InMemoryUploadedFile 对象——所以调用内置的 django 函数来保存这个文件非常简单。当您在 request.POST QueryDict 中有大量数据并且似乎没有直接的方法将其转换为 .zip 文件时,就会出现问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2016-03-15
    • 2014-04-03
    • 2014-07-12
    相关资源
    最近更新 更多