• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

245
Views
Django: muestra los datos obtenidos a través de una llamada ajax en html

Soy bastante nuevo en django y tengo problemas para hacer algo simple. Estoy creando un mapa con visualización de datos, le muestro al usuario un mapa svg simple que ayudará a hacer lo siguiente: 1 usuario hará clic en una de las áreas del mapa Se mostrará la visualización de 2 datos de esa área específica seleccionada.

Primero, envío el nombre del área (que obtuve de la ruta svg) con Jquery, llamada ajax a python, este es mi main.js:

 $(document).ready(function(e) { $('path').on('focus', function(e) { e.preventDefault(); $('#selection').html($(this).attr('name')); var gov = $('#selection').text(); console.log(gov) var obj = { gov} $.ajax({ type: 'POST', url: '/map/', contentType: 'application/json; charset=utf-8', //EDITED data: gov, success: function(data) {}, error: function(rs, e) { } }); }); });

Luego, envío el nombre a python. Así es como se ve mi views.py :

 [views.py][1] from django.shortcuts import render import numpy as np import pandas as pd from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def map(request): if request.method=='POST': data = request.body.decode("utf-8") gover=str(data) print(gover) df = pd.read_csv('https://raw.githubusercontent.com/-/datandvi/main/ndvid.csv', encoding='utf-8',na_values=None) d = df[(df['Date'] >= '1984-01-01') & (df['Date'] <= '1985-01-01') & (df['Province'] ==gover )] print(d) datadate = d[['Date']].values.tolist() dataplot = d[['Data_long_term_Average']].values.tolist() def numpy_flat(a): return list(np.array(a).flat) k = numpy_flat(dataplot) k1 = numpy_flat(datadate) context={ 'gover':gover,'k': k, 'k1': k1 } return render(request,'index.html',context) else: return render(request,'index.html')

aquí

Cada vez que selecciono una región, los datos que quiero mostrar se imprimen en los datos del terminal del área seleccionada pero no se envían a la página html, la variable de contexto está vacía . ¿Puedes ayudarme? aquí está mi index.html

-- urls.py

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

No podría proporcionar la respuesta exacta a menos que agregue sus plantillas, pero puedo ayudarlo a limpiar un poco su código.

Prueba a continuación y házmelo saber:

principal.js

 $(document).ready(function(e) { $('path').on('focus', function(e) { e.preventDefault(); $('#selection').html($(this).attr('name')); const gov = $('#selection').text(); console.log(gov) let obj = gov $.ajax({ type: 'POST', url: '/map/', contentType: 'json', // or try deleting this line data: { 'gov': gov }, success: function(data) { console.log(data); console.log(data.gov); console.log(data.k); }, error: function(data) { console.log('error', data) } }); }); });

vistas.py

 @csrf_exempt def map(request): if request.method=='POST': data = request.POST.get('gov') gover=str(data) print(gover) #this prints to your command prompt df = pd.read_csv('https://raw.githubusercontent.com/-/datandvi/main/ndvid.csv', encoding='utf-8',na_values=None) d = df[(df['Date'] >= '1984-01-01') & (df['Date'] <= '1985-01-01') & (df['Province'] ==gover )] print(d) datadate = d[['Date']].values.tolist() dataplot = d[['Data_long_term_Average']].values.tolist() def numpy_flat(a): return list(np.array(a).flat) k = numpy_flat(dataplot) k1 = numpy_flat(datadate) data={ 'gover':gover, 'k': k, 'k1': k1 } return JsonResponse(data, status=200) return redirect('/index.html/')
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error