We all know that when inputting time the colon sign is a distracting action. I would love is Django accepted EG 1800 as time converting it automatically to 18:00. Is there a way to set this as an overall behavior?
I already set this in settings.py: TIME_INPUT_FORMATS = [‘%H:%M’]
Same counts for dates EG 1210 converting automatically to 12-10-2023 always using the current year.
I’ve never tried this, did you try adding '%H%M
to TIME_INPUT_FORMATS
?
For the date, I think you’re probably going to need to validate / adapt that yourself with a custom widget with a custom to_python
method. You could try adding '%m%d'
to DATE_INPUT_FORMATS
, but you’re still going to need to apply the year yourself before converting it to a date object.
It seems that does not work. I now have these 2 widgets that do the job now:
# WIDGET TO ACCEPT SIMPLE DATE INPUT
class SmartDateField(forms.DateField):
widget = SmartDateInput
def to_python(self, value):
if value in self.empty_values:
return None
current_year = datetime.now().year
if isinstance(value, str) and re.match(r'^\d{4}$', value):
value = f"{value[:2]}-{value[2:]}-{current_year}"
# Use the parent class's to_python method to handle validation
return super().to_python(value)
# WIDGET TO ACCEPT SIMPLE TIME INPUT
class SmartTimeField(forms.TimeField):
widget = SmartTimeInput
def to_python(self, value):
if value in self.empty_values:
return None
if isinstance(value, str) and re.match(r'^\d{2,4}$', value):
if len(value) == 2:
value += "00" # If only two digits, it's the hour. Append '00' for minutes.
value = f"{value[:2]}:{value[2:]}" # Convert to HH:MM format
# Use the parent class's to_python method to handle validation
return super().to_python(value)