2

我正在尝试实现一个DateTimePicker小部件。

小部件

class DateTimeWidget(forms.DateTimeInput):
  class Media:
    js = ('js/jquery-ui-timepicker-addon.js',)
  def __init__(self, attrs=None):
    if attrs is not None:
      self.attrs = attrs.copy()
    else:
      self.attrs = {'class': 'datetimepicker'}

形式

class SessionForm(forms.ModelForm):
  class Meta:
    model = Event
    widgets = {'start_time': DateTimeWidget(),
               'end_time': DateTimeWidget()}

模板

{{ form.media }}
<form action="/event/post" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
<script type="text/javascript">
  $('.datetimepicker').datetimepicker({
    dateFormat: 'yy-mm-dd'
  });
</script>

DateTimePicker 渲染得很好,但格式是默认的%Y-%m-%d %H:%M:%S

我怎样才能删除秒(有%Y-%m-%d %H:%M)?


编辑

我试图得到

<input type="text" class="datetimepicker" value="2012-04-18 11:01" />

代替

<input type="text" class="datetimepicker" value="2012-04-18 11:01:05" />
4

1 回答 1

4

format为您的DateTimeInput实例提供参数:

class DateTimeWidget(forms.DateTimeInput):
  class Media:
    js = ('js/jquery-ui-timepicker-addon.js',)
  def __init__(self, attrs=None):
    if attrs is not None:
      self.attrs = attrs.copy()
    else:
      self.attrs = {'class': 'datetimepicker'}

    if not 'format' in self.attrs:
        self.attrs['format'] = '%Y-%m-%d %H:%M'

如果字典中没有给出规范,这将默认为您想要的format字符串:formatattrs

In [1]: dw = DateTimeWidget()

In [2]: dw.render("foo", "bar")
Out[1]: u'<input value="bar" type="text" class="datetimepicker" \
  name="foo" format="%Y-%m-%d %H:%M" />'

如果需要,您可以覆盖格式,例如%Y-%m-%d

In [3]: dw = DateTimeWidget({'format': "%Y-%m-%d"})

In [4]: dw.render("foo", "bar")
Out[4]: u'<input type="text" name="foo" value="bar" format="%Y-%m-%d" />'

要操作方法value内部.render(),您可以使用:

In [5]: dw = DateTimeWidget()

In [6]: now = datetime.now()

In [7]: dw.render("foo", now.strftime('%Y-%m-%d %H:%M'))
Out[7]: u'<input value="2012-04-19 17:17" type="text" class="datetimepicker" \
  name="foo" format="%Y-%m-%d %H:%M" />'

render或者您可以像这样覆盖DateTimeWidget

  def render(self, name, value, attrs=None):
    value = value.strftime(self.attrs['format'])
    return super(forms.DateTimeInput, self).render(name, value, attrs)

这将给出以下输出(无需调用.strftime()):

In [8]: dw = DateTimeWidget()

In [9]: dw.render("foo", datetime.now())
Out[9]: u'<input value="2012-04-19 17:27" type="text" class="datetimepicker" \
  name="foo" format="%Y-%m-%d %H:%M" />'

希望有帮助。

于 2012-04-19T14:57:20.663 回答