Django + Ajax | File Download | Server does not recognize Ajax request

I am trying to implement file upload using ajax with Django, but encountering some problems.

When a user tries to upload files after selecting a file and submitting the form, then, according to my understanding, the ajax request should be sent to the server using the method POST, but in my case the request POSTis made to the server, but the server cannot identify it as an ajax request, and the browser redirected to http://<server>:<port>/upload/, and the content on this page is as follows.

{"status": "error", "result": "Something went wrong.Try Again !!"}

Django Version: 1.6.2

Python Version: 2.7.5

In addition, testing on the Django Development Server.

views.py

def upload(request):
        logging.info('Inside upload view')
        response_data = {}
        if request.is_ajax():
                logging.info('Is_AJAX() returned True')
                form = UploaderForm(request.POST, request.FILES)

                if form.is_valid():
                        logging.info('Uploaded Data Validated')
                        upload = Upload( upload=request.FILES['upload'] )
                        upload.name = request.FILES['upload'].name
                        upload.save()
                        logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)

                        response_data['status'] = "success"
                        response_data['result'] = "Your file has been uploaded !!"
                        response_data['fileLink'] = "/%s" % upload.upload

                        return HttpResponse(json.dumps(response_data), content_type="application/json")

        response_data['status'] = "error"
        response_data['result'] = "Something went wrong.Try Again !!"

        return HttpResponse(json.dumps(response_data), content_type='application/json')

Template

<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
                {% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>

Javascript 1:

$('#uploadForm').submit(function(){

        var formData = new FormData($(this)[0]);
        $.ajax({
                url: '/upload/',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                alert(data)
                },
                cache: false,
                contentType: false,
                processData: false
        });
        return false;
});

Javascript 2

var options = {
      url: '/upload/',
      type: "POST",
       error: function(response) {
               alert('Something went Wrong. Try Again');
        },
        success: function(response) {
            if ( response.status == 'success' ) {
              alert('success');
             }
        }
};

$('#uploadForm').ajaxSubmit(options);

Question:

1) Django ajax, request.is_ajax() False.

2) ajax, ?

, .

+4
3

, javascript

$('#uploadForm').submit(function(){

    var formData = new FormData($(this)[0]);
    $.ajax({
            url: '/upload/',
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
            alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
    });
    return false;
});

uploadForm html DOM . , , , , , POST.

+2

. jquery.form.js

$("#uploadForm").submit(function(event) {
    $(this).ajaxSubmit({
        url:'{% url upload_file %}',
        type: 'post',
        success: function(data) {
            console.log(data)
        },
        error: function(jqXHR, exception) {
            console.log("An error occurred while uploading your file!");
        }
    });
    return false;
});

.

+4

1) is_ajax() ? JQuery (jquery.form.js)? ajaxSubmit() .

http://jquery.malsup.com/form/

, HTTPRequest

Django HttpRequest.is_ajax() True, XMLHttpRequest. javascript ajax, . "HTTP_X_REQUESTED_WITH", , Django XMLHttpRequest .

2) ?

, JQuery ajax . , ajaxSubmit() $(# uploadForm).submit()

 $('#uploadForm').submit( function (){
     $(this).ajaxSubmit(options);
 return false;
 });

Hope this was helpful :)

-1
source

Source: https://habr.com/ru/post/1535788/


All Articles