Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
How to get value from Django view into Ajax success function

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda