0

To give you a better understanding consider my ajax request:

$.ajax({
    url: '{% url "validate-upload-single" %}',
    type: "POST",
    data: JSON.stringify({
        'mainForm': Myform,
        'currentForm': 1,
    }),
    dataType: 'json', // response type

Where:
var Myform = new FormData( $(this)[0] );

The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend

DJANGO VIEW:

print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')

RESULT:

SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}

I've tried $("form").serializeArray() but this only return text data, files seem to be missing

Lil boat
  • 119
  • 1
  • 4
  • 14

2 Answers2

0

I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax

vitaliy kotov
  • 570
  • 3
  • 5
  • Tried that and got the error: django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None – Lil boat Aug 19 '20 at 19:52
0

In the .js file you HAVE TO add the fist block of csrf token for properly working.

//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

Then you use json in you ajax, getting the template that you want to display by variable here "html_form":

// Submit post on submit
$('#post-form').on('submit', function(event){
    event.preventDefault();
    console.log("form submitted!")  // sanity check

    //Send data to server for getting back sorted
    $.ajax({
        url: '/schedule/sort_group/',
        async: true,
        type: 'post',
        data: { //data sent with the post request
            group_field_value: $("#select_group").children("#group-option:selected").val(),
            lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
        },
        dataType: 'json',
        success: function (data) {
        $("#change_by_select").html(data.html_form);

        }
    });
});

In the views.py file at the bottom you need to determine the data like that:

data['html_form'] = render_to_string('schedule/select_sort.html', context, 
request=request)
    return JsonResponse(data)

So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates). I hope it would help. Feel free to ask any questions.

GuuMee
  • 1
  • 1
  • Problem with this is that my form has a LOT of fields most include files...so unpacking manually would be rather redundant – Lil boat Aug 19 '20 at 19:51