Home > other >  How to get value from Django view into Ajax success function
How to get value from Django view into Ajax success function

Time:11-24

I have a django application where a user can upload a file on form submit. When the file is uploaded the program will get the column names from the csv file and display that in the Django Template

This is my views

def handle_new_file(request):
    if (request.method == 'POST'):
        form = NewFileForm(request.POST, request.FILES)
        
        if form.is_valid():
            csv_file = request.FILES['csv_file']

            fs = FileSystemStorage()
            file_name = fs.save(csv_file.name, csv_file)
            file_url = f"./media/file_uploads/{file_name}"
            
            print(file_name)
            print(file_url)
            
            cols = get_column_names(file_url)
            form.save()

        return HttpResponse(cols)

While the above view is called successfully on form submit, I am not able to pass this cols data back to the template. Here is my Ajax code

function upload(event) {
    event.preventDefault();
    var data = new FormData($('form').get(0));

    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            alert(data);
        }
    });
    return false;
}

$(function () {
    $('#new_form').submit(upload);
});

What am I doing wrong?

CodePudding user response:

You can make use of a JsonResponse [Django-doc] where you return the result as a JSON blob:

def handle_new_file(request):
    if request.method == 'POST':
        form = NewFileForm(request.POST, request.FILES)
        
        if form.is_valid():
            csv_file = request.FILES['csv_file']

            fs = FileSystemStorage()
            file_name = fs.save(csv_file.name, csv_file)
            file_url = f"./media/file_uploads/{file_name}"
            
            print(file_name)
            print(file_url)
            
            cols = get_column_names(file_url)
            form.save()

    return JsonResponse({'cols': cols})

then in the AJAX call, you can access the object with:

$.ajax({
    # …
    success: function (data) {
        console.log(data.cols);
    }
});

Of course in reality you process data.cols, and likely do not log the content of the list.

  • Related