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

0

244
Views
Django : display data got via ajax call on html

I am quite new to django and struggling to do something simple.I'm building map with data visualisation,I am showing the user a simple svg-map that will help in doing the following: 1-user will click on one of the areas of the map . 2-data visualisation of that specific selected area will be displayed.

First,i send the name of the area( that i got from svg path ) with Jquery,ajax call to python, this is my 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) {
          }
      });
    });
  
  });    

Then, i send the name to python, This is how my views.py looks like:

[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')   

here

Every time i select on region , the data that i want to display is printed in terminal data of the selected area is printed but not sent to html page,the context variable is empty . Can you please help ? here is my index.html

--urls.py

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

I wouldn't be able to provide the exact answer unless you add your templates but I can help clean up your code a bit.

Try below and let me know:

main.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)
        }
        });
    });
}); 

views.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