简体   繁体   中英

How to correctly get variables from Django to javascript and do a GET ajax call on a Django URL?

I apologize if I butchered the terms there. I'm learning webdev and I still don't understand how these technologies work together, so I'm writing everything that might contribute to the problem.

Here's where I'm at right now:

The urlpatterns in sites/urls.py :

urlpatterns += [
    path('api/test/<str:crop>/<str:category>/<str:date_from>/<str:date_to>/', data.get_test_page_data),
    path('test/<str:item>/<str:category>/<str:date_from>/<str:date_to>/', data.render_initial_test_page)
]

The functions in data.py :

def get_test_page_data(item, category, date_from, date_to):
   date_from = datetime.datetime.strptime(date_from, "%Y-%m-%d")
   date_to = datetime.datetime.strptime(date_to, "%Y-%m-%d")

   data = Items.objects.all().filter(item=item, category=category, date__range=[date_from, date_to])

   context = {
      "data" : data,
   }
   
   return JsonResponse(context)

def render_initial_test_page(response, item, category, date_from, date_to):
   ...
   context = {
      "item" : item,
      "category" : category,
      "date_from" : date_from,
      "date_to" : date_to
   }
   return render(response, 'sites/test.html', context)

The test.js :

var sites, map;
var test_data;

var item = '{{ item }}';
var category = '{{ category }}';
var date_from = '{{ date_from }}';
var date_to = '{{ date_to }}';

getTestData();

function getTestData() {
   $.ajax({
      method: 'GET',
      url: '/api/test/' + item + '/' + category + '/' + date_from + '/' + date_to + '/',
      success: function(data) {
        test_data = data;
        renderTestData();
      }
   });
}

The problem:

It doesn't work. It should render two objects in the test page, one Google Maps with markers on where the item is last seen and the list of items. Nothing renders on the map, and nothing is retrieved from the list.

I checked the Django terminal in IDE, and while it got everything right, there's an additional parameter or something:

GET /test/car/used/2019-03-01/2021-03-01/type

But if I have used a function with no parameters such that:

In sites/urls.py :

...
path('api/test/', data.get_all_test_page_data),
...

In test.js :

...
url: '/api/test/'
...

And lastly in data.py :

def get_test_page_data():
   data = Items.objects.all()

   context = {
      "data" : data,
   }

   return JsonResponse(context)

It works. So somewhere in getting the variables to sending it is wrong.

I'm stumped here. I searched for the code for anything that writes type but there's nothing. Did I overlook something or is there a better way to do this?

The goal is for the render_initial_test_page to load the easy basic info to be displayed on the website instantly, while the get_test_page_data will display the rest after a while.

EDIT:

console.log() output from Firefox:

car        2019-03-31:36:13
used       2019-03-31:37:13
2019-03-01 2019-03-31:38:13
2019-03-31 2019-03-31:39:13

Items in models.py :

class Items(models.Model):
    id = models.AutoField(primary_key=True)
    tag = models.CharField(max_length=50, unique=True)
    category = models.CharField(max_length=20)
    item = models.CharField(max_length=20)
    date = models.DateField()
    longitude = models.FloatField()
    latitude = models.FloatField()

Note that the following isn't your /api/ URL, so it's not being called by the ajax function:

GET /test/car/used/2019-03-01/2021-03-01/type

UPDATED

Your urlpattern for the api contains a value named crop , but the view contains one named category . This will normally raise an error.

# urls.py
path('api/test/<str:crop>/<str:category>/<str:date_from>/<str:date_to>/', data.get_test_page_data),

# data.py
def get_test_page_data(item, category, date_from, date_to):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM