Formats in a DateField working with a Rest Framework serializer

0

I have a problem with a date (DateBaja) because in this case it is a field that can be blank.

In the frontend I use a datepicker for that date field, the format of the datepicker is specified to dateFormat: 'dd/mm/yy', But the format in which the serializer returns the data is yyyy-mm-dd

Until now I had been using dates in this format yyyy-mm-dd and I had not been given this case.

To change this I have specified in the serializer how it should be the format of the dates.

The problem is that I can not empty the field, that is, if I put 01/01/2018 and then I want to delete this date from the input, it tells me that the empty field does not match the format.

I include part of the model and the serializer

Model:

class Contrato(models.Model):
    FechaContrato = models.DateField(null = True, blank = False)
    FechaRenovacion = models.DateField(null = True, blank = False)
    Renovado = models.BooleanField(default = False, blank = True)
    Baja = models.BooleanField(default = False, blank = True)
    FechaBaja = models.DateField(null = True, blank = True)

Serializer:

class ContratoEditSerializer(serializers.ModelSerializer):   
    FechaContrato = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y', 'iso-8601'])
    FechaRenovacion = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y', 'iso-8601'])
    FechaBaja = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y','iso-8601'])

    class Meta:
        model = Contrato

If I comment the line DateBaja of the serializer, and remove the datepicker from that input, it works correctly, that is, it allows me to empty the field when necessary. That if, when specifying a date, I must do it with the default date format in which the rest framework is working YYYY [-MM [-DD]]

What is the best way to approach this?

Thanks for help!

    
asked by Cecilio Alonso 05.06.2018 в 18:30
source

1 answer

0

I do not know if this is the best way, but for now I have raised the following in the serializer:

class ContratoEditSerializer(serializers.ModelSerializer):

    def to_internal_value(self, instance):
        a = super().to_internal_value(instance)
        if str(a['FechaBaja']) == '1900-01-01':
            a['FechaBaja'] = None
        return a

    FechaContrato = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y', 'iso-8601'])
    FechaRenovacion = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y', 'iso-8601'])
    FechaBaja = serializers.DateField(format="%d/%m/%Y", input_formats=['%d/%m/%Y', 'iso-8601',''])

The question is that built the serializer like this, if I leave the input blank, internally to the method to_internal_value comes to it DateBaja with the value '1900-01-01', and so I identify it to delete the value of DateBaja.

I do not know why he assigns '1900-01-01', but at the moment it's functional.

    
answered by 06.06.2018 / 13:41
source