Can someone please assist me with this issue? I am new to Django and I've been trying to create a web-based application which gets the user location and displays the shops around them from the tutorial I followed online. However, the initial values were hard-coded in the views.py in order to change the user's location. I've asked a question before in order to find the best solution to this, and the kind people advised to use AJAX. I've been trying to come up with a solution for few hours now and its driving me insane. I have never used AJAX before so I apologize for this.
This is what I have so far, no issues or errors when running the application, however, the values are not changing for user's location
Please see attached code
views.py
user_location = Point(0, 0, srid=4326)
def process_loc(request):
lat = float(request.GET.get('lat'))
lon = float(request.GET.get('lon'))
global user_location
user_location = Point(lat, lon, srid=4326)
return render(request, 'shops/index.html', {'lat': lat, 'lon': lon})
class Home(generic.ListView):
model = Shop
context_object_name = 'shops'
queryset = Shop.objects.annotate(distance=Distance('location',
user_location)
).order_by('distance')[0:15]
template_name = 'shops/index.html'
As it can be seen I'm declaring the user_location is located outside the function and then changing it inside the function, so it can be used in Home class
index.html
<head>
<meta charset="utf-8">
<title>Shops</title>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
var lat, lon;
lat = 100.347541;
lon = -87.321;
$.ajax({
type: "GET",
url: 'process_loc',
data:{
'lat': lat,
'lon': lon,
},
dataType : "json",
success: function(stores) {
// do whatever in here for success, errors
}
})
})
</script>
</body>
I am using this code for AJAX, at the moment I just hardcoded the values in HTML just to get it working first as I am desperate to find a solution for this.
urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.Home.as_view()),
path('', include('pwa.urls')),
path("search/", views.SearchResultsView.as_view()),
path('process_loc', views.process_loc, name='process_loc'),
]
Output when the server is ran
[06/Dec/2019 12:00:57] "GET / HTTP/1.1" 200 11312
[06/Dec/2019 12:00:57] "GET /process_loc?lat=100.347541;&lon=-87.321 HTTP/1.1" 200 6621
[06/Dec/2019 12:00:58] "GET /manifest.json HTTP/1.1" 200 342
[06/Dec/2019 12:00:59] "GET /serviceworker.js HTTP/1.1" 200 3228
I will appreciate any response on this and I apologise for the messy code, thank you.