Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework DateField format

I have drf model which is containe DateField. That field default format is "YYYY-MM-DD" just i want to convert "DD-MM-YYYY" how can is possible.

models.py

class Reminder(BaseModel):
    content = models.TextField()
    schedule_date = models.DateField()
    schedule_time = models.TimeField()
    is_release = models.BooleanField(default=True)

serializer.py

class ReminderSerializer(HyperlinkedModelSerializer):
    schedule_date = serializers.DateField(format="%d-%m-%Y")
    class Meta:
        model = Reminder
        fields = ('id','content','created_at','schedule_date','schedule_time','user_id','is_release','is_deleted',)

in serializer.py i just give the format but that format convering only in List page. as you can see listing is okey but the POST action field is not converted. API please look at image

like image 907
Jackquin Avatar asked Jan 25 '18 13:01

Jackquin


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is Django REST Framework architecture?

Django REST framework is an open source, flexible and fully-featured library with modular and customizable architecture that aims at building sophisticated web APIs and uses Python and Django.

What is Django REST Framework serializer?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is Django REST Framework APIView?

REST framework provides an APIView class, which subclasses Django's View class. APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.


1 Answers

You can take a look at DRF's docs on this. Basically format only deals with output, but for input you need to include input_formats - for your case you can do schedule_date = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y', 'iso-8601'])

It's up to you whether you want to keep the iso-8601 there.

like image 174
Thomas Jiang Avatar answered Sep 18 '22 23:09

Thomas Jiang