user9714967
user9714967

Reputation: 1962

I can not change the date format in django drf

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.

from rest_framework import serializers
from.models import SpaUser
from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer
import datetime
from rest_framework.settings import api_settings



class SpaUserSerializer(serializers.ModelSerializer):

    date_joined = serializers.ReadOnlyField()
    birthdate = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y',])

Upvotes: 10

Views: 20822

Answers (7)

Dhia Shalabi
Dhia Shalabi

Reputation: 1540

We have to differentiate between all these:

  1. DATE_INPUT_FORMATS

    To specify the date format for the input in POST request API.

  2. DATETIME_FORMAT

    To specify the DateTime format for serialized data like with GET request.

  3. DATE_FORMAT

    To specify the Date format for serialized data like with GET request.

And this is an example of how to use these settings in the settings.py file.

REST_FRAMEWORK = {
    'DATE_INPUT_FORMATS': ["%Y-%m-%d %H", ],
    'DATETIME_FORMAT': '%Y-%m-%d %H',
    'DATE_FORMAT': '%Y-%m-%d %H'
}

Note: You should use these settings just if you want your serializer to have the same data or DateTime format.

But in case you have changed in some field you can just change the format for that field and here is an example of how to do like this:

class YourSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        representation = super(YourSerializer, self).to_representation(instance)
        representation['created_at'] = instance.created_at.strftime('%Y-%m-%d %H)
        return representation

Or in a similar way

class YourSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%Y-%m-%d %H')

Upvotes: 2

Davy
Davy

Reputation: 1796

In settings.py include:

REST_FRAMEWORK = {  
    'DATE_FORMAT': '%d-%m-%Y'
}

Upvotes: 0

Jake
Jake

Reputation: 96

Although this thread is quite old, I found it when trying to solve a similar problem. Although the responses didn't give me the entire answer, they did push me to simply read DRF's quite helpful documentation on the topic:

https://www.django-rest-framework.org/api-guide/settings/#date-and-time-formatting

In my case, I am building a events calendar using Vuetify's v-calendar, Vue JS, and DRF. The v-calendar requires the format YYYY-MM-DD HH:MM, and prefers a string. I could simply store the string in my DB, but I preferred to store the datetime fields in native Python formatting for server-side processing should I ever need them. So, in my settings.py file, I added the following to my REST_FRAMEWORK setting:

'DATETIME_INPUT_FORMATS': ['%Y-%m-%d %H:%M',],
'DATETIME_FORMAT': '%Y-%m-%d %H:%M',

The first one takes a list (hence the brackets and comma), the second just takes a string. Then, in my serializer, I use:

start = serializers.DateTimeField()

On the front end, I take in the dates as the string objects, pass them to the calendar for display, and it works. When POSTing data, I simply pass them back in that same string format, and the DRF serializer encodes them as native Python for storage.

Upvotes: 1

SamwelOpiyo
SamwelOpiyo

Reputation: 388

If it is universal, in your settings file add "DATE_INPUT_FORMATS" to REST_FRAMEWORK settings like:

REST_FRAMEWORK = {
    "DATE_INPUT_FORMATS": ["%d-%m-%Y"],
    ...
}

for more details check http://www.django-rest-framework.org/api-guide/settings/#date-and-time-formatting

Upvotes: 22

user9714967
user9714967

Reputation: 1962

By combining all your solutions, it works

REST_FRAMEWORK = {
    # "DATE_INPUT_FORMATS": "%d-%m-%Y", doesn't works
    'DATE_INPUT_FORMATS': [("%d-%m-%Y"),],it works
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

Upvotes: 2

Lemayzeur
Lemayzeur

Reputation: 8525

To have it correctly work, input_formats is the argument you need to assign the format needed, format is the output format

birthdate = serializers.DateField(input_formats=['%d-%m-%Y',])

or you can set the default input format in your settings

DATE_INPUT_FORMATS = [
    ("%d-%m-%Y"),
]

Upvotes: 8

iklinac
iklinac

Reputation: 15738

From DRF documentation regarding DateField

Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')

So in your case format should be

format="%d-%m-%Y"

Upvotes: 1

Related Questions