Установка значения виджета карты GeoDjango в форме изменения на основе другого поля с помощью jQuery
Я работаю над проектом, который использует GeoDjango и django-cities. У меня есть одна модель:
class Site(models.Model):
name = models.CharField(max_length=60)
assigned_to = models.ForeignKey(
to=User, on_delete=models.PROTECT, null=True, blank=True
)
country = models.ForeignKey(
to=Country, on_delete=models.PROTECT, null=True, blank=True
)
# Region selection should be limited to country
region = ChainedForeignKey(
to=Region,
chained_field="country",
chained_model_field="country",
on_delete=models.PROTECT,
null=True,
blank=True,
)
# City selection should be limited to region
city = ChainedForeignKey(
to=City,
chained_field="region",
chained_model_field="region",
on_delete=models.PROTECT,
null=True,
blank=True,
)
location = PointField(null=True, blank=True)
Вот планируемый рабочий процесс:
- User sets the country of the site
- User sets the region of the site (selection is limited by country)
- User sets the city of the site (selection is limited by region)
- When the city changes, the point on the map widget for the
locationfield jumps to the location of the city - The user then fine-tunes the location manually and saves
Для достижения этой цели я добавил этот js файл, используя класс Media в SiteAdmin:
$(document).ready(function() {
$("select[name='city']").change(function(e) {
const cityId = e.target.value
geodjango_location.clearFeatures()
// Get the location of the selected city
$.ajax({
"type" : "GET",
"url" : `/sites/admin/city-location/${cityId}/`,
"dataType" : "json",
"cache" : false,
"success" : function(json) {
// Use the city's location as the value of the `location` field
$('#id_location').val(json)
},
})(jQuery)
})
})
При изменении города существующая точка очищается, и вызов ajax выполняется успешно. Я могу поставить точку останова и увидеть, что вызов API возвращает правильное местоположение в виде строки GeoJSON.
Сейчас есть две проблемы:
- Even though the breakpoint hits and I'm getting the correct JSON, I see this in the browser console:
Uncaught TypeError: $.ajax(...) is not a function
<anonymous> http://localhost:8000/static/admin/site.js:21
jQuery 2
dispatch
handle
site.js:21:11
<anonymous> http://localhost:8000/static/admin/site.js:21
jQuery 2
dispatch
handle
receiveMessage resource://gre/actors/SelectChild.jsm:272
receiveMessage resource://gre/actors/SelectChild.jsm:475
- Most importantly, after
$('#id_location').val(json), the location is not actually set to the point encoded injson. The existing point is just cleared. There are no error messages besides the one stating that ajax is not a function.
Обратите внимание, что я попытался переопределить базовый шаблон, шаблон формы изменения и шаблон модели, чтобы включить https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js, но сообщение об ошибке остается (несмотря на то, что фактический вызов ajax работает нормально).
Есть идеи?