I have a model and a serializer using DRF. With the code below, when a form is submitted via ajax with all the fields blank, I get an error for description
, "This field cannot be blank", which is exactly what I want. But for the Datetime fields, I get "Datetime has wrong format". Why isn't it giving me "This field cannot be blank" for the date time fields also? It's doing the format validation before it evaluates whether it's even got a value or not. According to the docs, Required
should be true by default, and it's also required on the Model.
How can I make it simply say "This field cannot be blank" or something similar? Right now I'm working around it by doing validation in the view that calls the serializer.
class RoomEventSerializer(serializers.ModelSerializer):
start_datetime = serializers.DateTimeField(input_formats=(['%m/%d/%Y %I:%M %p', 'iso-8601']))
end_datetime = serializers.DateTimeField(input_formats=(['%m/%d/%Y %I:%M %p', 'iso-8601']))
class Meta:
model = RoomEvent
fields = ('start_datetime', 'end_datetime', 'description', 'room', 'start_hour', 'start_min', 'start_ampm', 'end_hour', 'end_min', 'end_ampm', 'requesting_user', 'type', 'approval_status')
def validate(self, data):
if data['start_datetime'] >= data['end_datetime']:
raise serializers.ValidationError('Start date must be prior to end date.')
return data
class RoomEvent(models.Model):
description = models.CharField(max_length=250)
start_datetime = models.DateTimeField()
end_datetime = models.DateTimeField()
Which django-rest-framework version are you using? I think it is a bug solved for DateField
. See https://github.com/tomchristie/django-rest-framework/issues/2687
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With