Django - DateTime小部件格式

时间:2012-04-19 14:46:25

标签: django django-forms django-templates django-widget

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

的widget

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" />

1 个答案:

答案 0 :(得分:3)

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字典中没有给出format规范,则默认为您想要的attrs字符串:

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" />'

希望有所帮助。