blocjager
blocjager

Reputation: 77

Stop page from redirecting after form submission in Django

I am using django and I have created an app in which I want to upload a zip file which is saved in a specific location (At this point my django server is localhost) I have the following code which is working fine:

This is my HTML Template:

<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>

This is my forms.py:

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

This is my 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'),
]

But in the end, the url is changing to /upload_file - which is correct as I understand - and that page is empty (since I am returning an empty HttpResponse)

I am trying to build a Single-Page-Application and this redirection is throwing the entire state of my web-page out of the window.

Is there any way in which I can possible make an AJAX call instead of using django forms?

Thanks!

EDIT

I did add an ajax call that gets the uploaded file and sends it to the django view.

AJAX call:

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

But in the view when I print out request.POST, I get this mess (and many, many lines of it):

<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\

Upvotes: 1

Views: 2205

Answers (1)

Kyle Higginson
Kyle Higginson

Reputation: 942

You should use ajax for this, retrieve the data from the form, make the request and return false, which prevents the redirect from occurring. It should look this like this:

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

Upvotes: 1

Related Questions