Reputation: 613
I am trying to save time in this formate '13:21' . but django not letting me to do so and giving this exception
["'13 : 53' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."]
my field is
duration = models.TimeField(null=True , blank=True)
my setting.py
is
TIME_INPUT_FORMATS = ('%H:%M',)
Upvotes: 0
Views: 369
Reputation: 604
that's better to change your frontend and send data in correct format rather than changing backend, but if you want to handle that in backend side, you can override model save method and clear duration
spaces:
def save(self, *args, **kwargs):
if isinstance(self.duration, str):
self.duration = self.duration.replace(' ', '')
super().save(*args, **kwargs)
this will work as long as you pass duration
with string value, in other cases you may use datetime.datetime.strptime()
like:
import datetime
time_string = '13 : 53'
time = datetime.datetime.strptime(time_string, '%H : %M').time()
also this could happen anywhere (even in your API) before passing data to the model too.
Upvotes: 0
Reputation: 675
To make things work simply add this format to formats.
TIME_INPUT_FORMATS = ('%H : %M', '%H:%M')
As you can see the spaces are also counted in as characters for example you would like to format time only with spaces - its possible just bo doing this
TIME_INPUT_FORMATS = ('%H %M',)
Upvotes: 1