Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda