Home > Software engineering >  keyerror in drf serializer
keyerror in drf serializer

Time:10-26

I have a serializer like this :

class LocationSerializer(serializers.Serializer):
    
    lat = serializers.DecimalField(max_digits=9, decimal_places=6),
    lng = serializers.DecimalField(max_digits=9, decimal_places=6),
    term = serializers.CharField(max_length=100)

in views.py :

@api_view(['POST'])
def get_prefer_locations(request):        
    serilizer = LocationSerializer(data=request.data)
    if serilizer.is_valid():
        print(request.data)
        location_obj=Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term'])
        address = location_obj.convert_latandlong_to_address()

and this is the Location class that i have defined :

class Location:
    def __init__(self, latitude,longitude,term):
        self.lat = latitude,
        self.lng=longitude,
        self.term=term
        
    def convert_latandlong_to_address(self):

        geolocator = Nominatim(user_agent="geoapiExercises")
        location = geolocator.reverse(self.lat "," self.lng)
        address = location.raw['address']
        return address

when i printed request.data in terminal i got this :

{'lat': '29.623411959216355', 'lng': '52.49860312690429', 'term': 'cafe'}

but i got this error :

  File "/home/admin1/mizbanproject/location/preferlocation/api/views.py", line 15, in get_prefer_locations
    location_obj = Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term'])
KeyError: 'lat'

and this is the json i am sending via postman:

{
    "lat":"29.623411959216355",
    "lng":"52.49860312690429",
    "term":"cafe"
}

CodePudding user response:

Since you're validating your serializer, the validated data should be accessible in validated_data:

location_obj=Location(serilizer.validated_data['lat'],serilizer.validated_data['lng'],serilizer.validated_data['term'])

CodePudding user response:

I changed the serilizers to below and it works the problem was in max_digits and decimal_places :

class LocationSerializer(serializers.Serializer):

    lat = serializers.DecimalField(max_digits=25,decimal_places=15)
    lng = serializers.DecimalField(max_digits=25, decimal_places=15)
    term = serializers.CharField(max_length=100)
  • Related