After hours of searching, I found many posts that are related but wasn't able to help.
What I want to do is input eg: 10:30 AM into the TimeField.
In the django rest framework API on the browser, it is using this 10:30 AM format ('%I:%M %p'
).
But when I am using postman to test it, the output is in 24hr format ('%H:%M:%S'). I also tried to use 10:30 PM as input but the output I get is 10:30:00 instead of 22:30:00.
Many of the answers I found suggest to change the TimeField format in settings.py
by using this line:
TIME_INPUT_FORMATS = ('%I:%M %p',)
but it doesn't work for me.
Sorry for my inexperience on django rest framework as I am still learning.
Here is the screenshot of the result. On browser API:
On postman:
Or you can write custom field and use it instead of default. class UserSerializer(serializers. ModelSerializer): created_at = serializers. DateTimeField(format='%Y') # add read_only=True to the field in case if date created automatically ...
In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.
Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
DEFAULT_AUTHENTICATION_CLASSES. A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.
If you check the documentation on the TimeField you will see:
Signature:
TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
Where
format
- A string representing the output format. If not specified, this defaults to the same value as theTIME_FORMAT
settings key, which will be'iso-8601'
unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python.
input_formats
- A list of strings representing the input formats which may be used to parse the date. If not specified, theTIME_INPUT_FORMATS
setting will be used, which defaults to['iso-8601']
.
So you either can specify the format
and input_formats
on the serializer, or set the settings.TIME_FORMAT
and settings.TIME_INPUT_FORMATS
.
Let's set the first case:
class MySerializer(serializers.Serializer):
...
birthTime=serializers.TimeField(format='%I:%M %p', input_formats='%I:%M %p')
Some suggestions:
birth_time
.You may need to play a bit around with the input format because you may expect many different inputs:
input_formats=['%I:%M %p','%H:%M',...]
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