views.py:
from django.shortcuts import render
from geopy.geocoders import Nominatim
from django.http import JsonResponse
Create your views here.
def single_address(request):
if request.method == 'POST':
#print(request)
address = request.POST.get('address','')
#print(type(address))
if address:
# Initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my_geocoder")
try:
# Geocode the address
location = geolocator.geocode(address)
if location:
# Extract latitude and longitude
latitude = location.latitude
longitude = location.longitude
return JsonResponse({'latitude': latitude, 'longitude': longitude})
else:
return JsonResponse({'error': 'Geocoding failed for the address'}, status=500)
except Exception as e:
return JsonResponse({'error': f'Error: {str(e)}'}, status=500)
else:
return JsonResponse({'error': 'Address not provided'}, status=400)
else:
# Render the HTML template for the form
return render(request, 'address/single_address.html')
single_address.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Coordinates for Single Address</title>
</head>
<body>
<h1>Get Coordinates for Single Address</h1>
<form id="addressForm">
{% csrf_token %}
<label for="address">Enter Address:</label>
<input type="text" id="address" name="address" required>
<button type="submit">Get Coordinates</button>
</form>
<div id="response"></div>
<script>
document.getElementById('addressForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
var address = document.getElementById('address').value;
// Make an AJAX request to the view
fetch("{% url 'single_address' %}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({ 'address': address })
})
.then(response => response.json())
.then(data => {
// Display the response
document.getElementById('response').innerText = JSON.stringify(data, null, 2);
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
对于此应用程序,我收到了错误的请求。在我的浏览器中,输入地址后,我得到的输出为 '{ “错误”:“未提供地址” }'.
帮助查找代码可能存在的问题,因为我不确定这里出了什么问题,为什么address = request.POST.get('address','') 无法检测到地址
request.POST
允许访问“POST params”(以 multipart/form-data
或 application/x-www-form-urlencoded
形式给出)。但是,您正在使用 application/json
。
要访问数据,您需要解析 JSON 内容,例如,
from json import loads
address = loads(request.body).get('address','')
FormData
作为 POST 数据提交
const form = new FormData();
form.set("address", address);
fetch(
url,
{
//...
body: form
}
)