You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整tempus_dominus DateTimePicker格式适配Django模型?

Fixing Tempus Dominus DateTimePicker Format Mismatch with Django DateTimeField

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 to 07/30/2020 4:33 PM as you requested.
  • Moving icons to display.icons: Tempus Dominus v5 organizes display-related settings under the display key, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:37:43