收到错误请求,在获取地址时返回空字符串

问题描述 投票:0回答:1

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','') 无法检测到地址

python html django view request
1个回答
0
投票

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
  }
)
© www.soinside.com 2019 - 2024. All rights reserved.