alexdzn
alexdzn

Reputation: 13

Django REST API serializer.is_valid() always returns false

I'm trying to make a POST request from the frontend to the backend through REST API. I'm passing as data a dictionary which contains all the fields of the table from the database

Data from frontend looks like this:

var state = {
  event: {
    name: "test",
    id_organizer: 1,
    start_date: "2019-11-11T11:11:11",
    end_date: "2019-12-11T11:12:11",
    location: "test",
    description: "test",
    id_type: 1,
    status: "pending",
  }
}

and POST request like this:

axios
      .post("http://127.0.0.1:8000/api/addevent", state.event)
      .then(response =>{
        console.log(response.data);
      }) 
      .catch(err => console.log(err));

Here is the model of the event:

class Event(models.Model):
   name = models.TextField()
   id_organizer = models.ForeignKey(User, on_delete=CASCADE, db_column='id_organizer')
   start_date = models.DateTimeField()
   end_date = models.DateTimeField()
   location = models.TextField()
   description = models.TextField()
   id_type = models.ForeignKey(EventType, on_delete=CASCADE, db_column='id_type')
   status = models.CharField(max_length = 50)
   class Meta:
      db_table="events"

Here is the database table

Here is the @api_view:

@api_view(['POST'])
def addevent(request):
   if request.method == "POST":
      data =  JSONParser().parse(request)
      serializer = EventSerializer(data=data)
      if serializer.is_valid():
         serializer.save()
         return Response({'saved':True},status=status.HTTP_201_CREATED)
      else:
         return Response({'saved':False}, status=status.HTTP_400_BAD_REQUEST)

Here is the serializer:

class EventSerializer(serializers.ModelSerializer):
class Meta:
    model = Event
    fields = '__all__'

The request happens but the function serializer.is_valid() always returns false and the response is always {'saved':False} I already validated the data that it is sent correct and when I printed it, I got the output:

{
   "name": "test",
   "id_organizer": 1,
   "start_date": "2019-11-11T11:11:11",
   "end_date": "2019-12-11T11:12:11",
   "location": "test",
   "description": "test",
   "id_type": 1,
   "status": "pending",
 }

This data is correct and I got the conclusion that the problem is with the "is_valid()" function. I've tried to hard-code the data from the api view but it ran into the same issue. I've already checked and tried most of the posts that exists on this topic and I cannot find my mistake.

Upvotes: 1

Views: 1285

Answers (1)

Souren Ghosh
Souren Ghosh

Reputation: 96

Your input datetime might not be getting validated with model Datetime field. You might need to change the date time format using strptime .

Upvotes: 1

Related Questions