Django JQuery AJAX Request Form

After reading other questions on a similar topic, I still do not understand what is wrong with this code.

I am testing code that uses the jQuery Form plugin. I added a call in the form of a template to display it for the first time so that the user can select a file and upload. But it never sends an AJAX request, so the section of code in the view is not executed. Although not shown here, the jQuery library and the jQueryForm plugin are indeed called.

Template:
<form id="uploadForm"  method="post" enctype="multipart/form-data">
                            {% csrf_token %}
        <input id="fileInput" class="input-file" name="upload" type="file">
        {{ form.docfile }}
        <span class="upload-message"></span>
        <input type="submit" value="Upload" />
</form>
<script>
    var message = '';
    var options = {
        type: "POST",
        url: '/upload/file/',
        error: function(response) {
            message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
            $('.upload-message').html(message);
            $('fileInput').val('');
        },
        success: function(response) {
            message = '<span class="' + response.status + '">' + response.result + '</span> ';
            message = ( response.status == 'success' ) ? message + response.fileLink : message;
            $('.upload-message').html(message);
            $('fileInput').val('');
        }
    };
    $('#uploadForm').ajaxSubmit(options);
</script>

View:

def upload(request):
    response_data = {}

    if request.method == 'POST':
        if request.is_ajax:
            form = UploaderForm(request.POST, request.FILES)

            if form.is_valid():
                upload = Upload(
                upload=request.FILES['upload']
            )
            upload.name = request.FILES['upload'].name
            upload.save()

            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'] = "We're sorry, but kk something went wrong. Please be sure that your file respects the upload conditions."

        return HttpResponse(json.dumps(response_data), content_type='application/json')
    else:
        form = UploaderForm()
        return render(request, 'upload.html', {'form': form})

It correctly calls the template for the first time, it displays the buttons, it runs the script again, but the form is invalid, so response_data is in error.

What am I missing?

Thanks Ricardo

+2
source share
3

API, :

$('#uploadForm').ajaxForm({
    beforeSubmit: function(a,f,o) {
        $('.upload-message').html('Submitting...');
    },
    success: function(data) {
        $('.upload-message').html('Done!');
    }
});

HTML:

<form id="uploadForm" action="/upload/file/" method="post" enctype="multipart/form-data">
                        {% csrf_token %}
    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
    File: <input type="file" name="file">
    {{ form.docfile }}
    <span class="upload-message"></span>
    <input type="submit" value="Upload" />
</form>
0

, , script .

var options = {
    type: "POST",
    url: '/upload/file/',
    data: new FormData(document.getElementById('uploadForm')),
    processData: false,
    contentType: false,
    error: function(response) {
        message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
        $('.upload-message').html(message);
        $('fileInput').val('');
    },
    success: function(response) {
        message = '<span class="' + response.status + '">' + response.result + '</span> ';
        message = ( response.status == 'success' ) ? message + response.fileLink : message;
        $('.upload-message').html(message);
        $('fileInput').val('');
    }
};
0

You have at least one problem with you:

if not request.GET:
    return render(request, 'upload.html') 

will prevent further execution when request.GETempty , which is the case when executing a POST request .

0
source

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


All Articles