Reputation: 253
I am developing a simple web application that utilizes the openweathermap api. There is an api call to a view that returns the api data, and displays the temp & description for the weather of the particular city that the user types in.
The api call below is another call for a new feature that allows the user to save a particular weather data of their choosing. It takes the temp & desc from the state, and sends it to the backend view. The view then saves that data into the database, and returns a Response that I will then use to display the data in the same api call. It is giving me a 400 error. I console logged the temp & desc and they both print out correct so I am not sending undefined data to the backend. Could it be the way I am serializing the data?
Front end api call
const saveWeather = (temperature, description) => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
temperature: temperature,
description: description
})
};
fetch("/api/savedweather", requestOptions)
.then((response) => {
if (response.ok) {
console.log("OK");
}
})
.catch((error) => {
console.log(error);
});
}
View
class SaveWeather(APIView):
serializer_class = WeatherSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
temperature = serializer.data.get('temperature')
description = serializer.data.get('description')
weather = Weather(temperature=temperature, description=description)
weather.save()
return Response(WeatherSerializer(weather).data, status=status.HTTP_201_CREATED)
return Response({'Bad Request': "Invalid Data..."}, status=status.HTTP_400_BAD_REQUEST)
Model
from django.db import models
class Weather(models.Model):
temperature = models.IntegerField(null=False, default=1)
description = models.CharField(max_length=50)
Serializer Class
from .models import Weather
from rest_framework import serializers
class WeatherSerializer(serializers.ModelSerializer):
class Meta:
model = Weather
fields = ('temperature', 'description')
Upvotes: 5
Views: 17912
Reputation: 1728
It is hard to tell without knowing the model and serializer definitions.
but since it clearly seems to be serializaer validation error, you can check the errors thrown by serializaers with serializer.errors
field.
if serializer.is_valid():
...
return Response(WeatherSerializer(weather).data, status=status.HTTP_201_CREATED)
print(serializer.errors)
Upvotes: 6