Add support for additional datetime input formats

The frontend library uses an datetime strong format for it's base language (US English)
that is not supported by Python's datetime. This commit adds custom formats to
support the frontend strings.
This commit is contained in:
Christopher C. Wells 2020-01-20 15:09:58 -08:00 committed by Christopher Charbonneau Wells
parent a93070c5ba
commit cc0eef33a8
5 changed files with 48 additions and 6 deletions

View File

View File

View File

@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
from django.utils.formats import get_format
# Adds support for datetime formats used by frontend.
formats = get_format('DATETIME_INPUT_FORMATS', lang='en')
DATETIME_INPUT_FORMATS = [
'%m/%d/%Y %I:%M:%S %p',
'%m/%d/%Y %I:%M %p'
] + formats

View File

@ -107,18 +107,19 @@ LOGIN_URL = '/login/'
LOGOUT_REDIRECT_URL = '/login/'
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
# Timezone
# https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/
LANGUAGE_CODE = 'en'
USE_TZ = True
TIME_ZONE = os.environ.get('TIME_ZONE', 'Etc/UTC')
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGE_CODE = 'en'
LOCALE_PATHS = [
os.path.join(BASE_DIR, "locale"),
@ -134,6 +135,14 @@ LANGUAGES = [
]
# Format localization
# https://docs.djangoproject.com/en/3.0/topics/i18n/formatting/
USE_L10N = True
FORMAT_MODULE_PATH = ['babybuddy.formats']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
# http://whitenoise.evans.io/en/stable/django.html

View File

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
import datetime
from django.core.exceptions import ValidationError
from django.forms.fields import DateTimeField
from django.test import TestCase
class FormatsTestCase(TestCase):
def test_datetime_input_formats(self):
field = DateTimeField()
supported_custom_examples = [
'01/20/2020 9:30 AM',
'01/20/2020 9:30:03 AM',
'10/01/2020 11:30 PM',
'10/01/2020 11:30:03 AM',
]
for example in supported_custom_examples:
result = field.to_python(example)
self.assertIsInstance(result, datetime.datetime)
with self.assertRaises(ValidationError):
field.to_python('invalid date string!')