在 Django Admin (jazzmin) 中使用 jQuery DateTimePicker 出现错误 - 输入值列表

Using jQuery DateTimePicker in Django Admin (jazzmin) get error - Enter a list of values

在 Django 管理中为 DateTimeField 插入 TempusDominus 小部件。任务是启用按月和年缩放的日期选择。标准小部件没有该选项。但是 Django 在使用 DateTimeField 时期望 return 两个值,一个带有日期,一个带有时间,但是小部件 return 的一个值 =“2021-07-27 13:00:00”。保存或修复支票时如何拆分值?有一个日期和时间值保存到数据库中。感谢您的帮助。

model.py

start_date = models.DateTimeField(blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)

widgets.py

from django.forms import DateTimeInput


class DateTimePicker(DateTimeInput):
    template_name = 'widgets/datetimepicker.html'

    def get_context(self, name, value, attrs):
        datetimepicker_id = f'datetimepicker_{name}'
        if attrs is None: attrs = dict()
        attrs['data-target'] = f'#{datetimepicker_id}'
        attrs['class'] = 'form-control datetimepicker-input'
        context = super().get_context(name, value, attrs)
        context['widget']['datetimepicker_id'] = datetimepicker_id
        return context

    class Media:
        css = {
            "all": (
                "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css",
                "//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/css/tempusdominus-bootstrap-4.min.css",
            )
        }
        js = (
            '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js',
            '//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/js/tempusdominus-bootstrap-4.min.js',
        )

widgets/datetimepicker.html

<div class="input-group date" id="{{ widget.datetimepicker_id }}" data-target-input="nearest">
  {% include "django/forms/widgets/input.html" %}
  <div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker">
    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
  </div>
</div>
<script>
  django.jQuery(document).ready(function ($) {
    $("#{{ widget.datetimepicker_id }}").datetimepicker({
      format: 'YYYY-MM-DD HH:mm:ss',
    });
  });
</script>

admin.py

formfield_overrides = { models.DateTimeField: {'widget': DateTimePicker}, }

小部件

保存时出错

你可以试试这个

在你的froms.py

class DateTime(ModelForm):
    start_date = forms.DateTimeField(
        input_formats=['%Y-%m-%d %I:%M:%S %p'],
        widget=forms.DateTimeInput(format='%Y-%m-%d %I:%M:%S %p')
    )

   end_date = forms.DateTimeField(
        input_formats=['%Y-%m-%d %I:%M:%S %p'],
        widget=forms.DateTimeInput(format='%Y-%m-%d %I:%M:%S %p')
    )

    
    class Meta:  
     model = your model name
     fields = ['start_date','end_date',your others fields....]

然后在 html

中加载 cdn link