如何调整tempus_dominus DateTimePicker格式适配Django模型?
I’ve run into this exact issue before—Tempus Dominus defaults to a display/submit format that doesn’t align with Django’s DateTimeField expectations, which causes validation errors when submitting forms. Here’s how to fix it by separating the user-facing display format from the backend-compatible submit format:
Step-by-Step Fix
Modify your publish_date field in forms.py to explicitly configure both formats, and adjust the icon settings to fit Tempus Dominus v5’s structure (your existing icons were under the wrong configuration key):
publish_date = forms.DateTimeField( widget=DateTimePicker( # Critical: Set the format Django expects to receive format='YYYY-MM-DD HH:mm', options={ 'useCurrent': True, 'collapse': False, # Configure display settings for the frontend 'display': { # The format users will see when interacting with the picker 'format': 'MM/DD/YYYY h:mm A', # Move your icon configs under display.icons 'icons': { 'time': 'fa fa-clock-o', 'date': 'fa fa-calendar', 'up': 'fa fa-arrow-up', 'down': 'fa fa-arrow-down', 'previous': 'fa fa-chevron-left', 'next': 'fa fa-chevron-right', 'today': 'fa fa-calendar-check-o', 'clear': 'fa fa-delete', 'close': 'fa fa-times' } } }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ) )
What This Does
format='YYYY-MM-DD HH:mm': This tells the Django widget to expect data in the exact format your model’s DateTimeField accepts (2020-07-30 16:33).display.format='MM/DD/YYYY h:mm A': This sets the user-visible format to07/30/2020 4:33 PMas you requested.- Moving icons to
display.icons: Tempus Dominus v5 organizes display-related settings under thedisplaykey, so your icons will render correctly with this structure.
Why This Works
Tempus Dominus handles converting between the display format (for user interaction) and the submit format (for Django) automatically. When the form is submitted, the picker sends the date/time in YYYY-MM-DD HH:mm format, which matches your model’s requirements, eliminating the validation error.
内容的提问来源于stack exchange,提问作者Voicu Mirel

