Search code examples
django-rest-frameworkdate-formattingdjango-serializerdatefield

DRF, set Date field format in serializer doesn't change the format


I have a Month model with a Date field:


class Month(models.Model):
    month = models.DateField(primary_key=True, unique=True)

    days = models.PositiveSmallIntegerField(default=0,
                                            validators=IntegerValidators.MONTH_VALIDATOR, )

    def __str__(self):
        return str(self.month)

And it's serializer:



class MonthSerializer(serializers.ModelSerializer):
    month = serializers.DateField(input_formats='%m-%Y', format='%m-%Y')

    class Meta:
        model = Month
        fields = '__all__'

But when trying to send a request like this:

{
  "month": "03-2020",
  "days": 12
}

I get this 400 response:

{
  "month": [
    "Date has wrong format. Use one of these formats instead: %, m, -, %, Y."
  ]
}

I don't want to set this as default in my setting.

And when I make a request in the browsable API this format is saved:

[
    {
        "month": "07-2020",
        "days": 23
    },
    {
        "month": "07-2020",
        "days": 22
    }
]

Solution

  • input_formats expects an iterable, use input_formats=['%m-%Y'] instead.