Search code examples
pythonhtmldjangoviewrequest

Getting BAD REQUEST, while fetching address it's returning empty string


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>

For this application, I am getting a bad request. In my browser, after entering the address, I getting the output as '{ "error": "Address not provided" }'.

Help to find what might be wrong with the code, as I am not sure what is wrong here, why address = request.POST.get('address','') can't detect address


Solution

  • request.POST give access the "POST params" (given as multipart/form-data or application/x-www-form-urlencoded). However, you are using application/json.

    To access the data, you'll need to parse the JSON content, E.g.,

    from json import loads
    address = loads(request.body).get('address','')
    

    Or, you can submit as POST data use the FormData

    const form = new FormData();
    form.set("address", address);
    fetch(
      url,
      {
          //...
          body: form
      }
    )