如何在Django中提供初始值时更改时间格式?

huangapple go评论63阅读模式
英文:

How to change the time format when providing an initial value in Django?

问题

我在Django中创建了一个表单,并在渲染表单时为时间字段提供了初始值,格式为HH:MM:SS,但如果我不提供任何初始值,格式将为HH:MM。我想指定一个初始值并希望格式为HH:MM。

class SearchTimeSlotsForm(forms.Form):
  available_from = forms.TimeField(
      widget=TimeInput(attrs={'class': 'unbold-form'}), 
      initial=time(0)
  )
  available_till = forms.TimeField(
      widget=TimeInput(attrs={'class': 'unbold-form'}), 
      initial=time(23,59,59)
  )

有人能帮助我吗?

英文:

I made a form in Django and provided an initial value to the time field when rendering the form, the format is HH:MM:SS but if I do not provide any initial value the format is HH:MM. I want to specify an initial value and want the format to be HH:MM.

class SearchTimeSlotsForm(forms.Form):
  available_from = forms.TimeField(
      widget=TimeInput(attrs={'class': 'unbold-form'}), 
      initial=time(0)
  )
  available_till = forms.TimeField(
      widget=TimeInput(attrs={'class': 'unbold-form'}), 
      initial=time(23,59,59)
  )

Can someone please help me with this?

答案1

得分: 0

widget 添加一个 format

class SearchTimeSlotsForm(forms.Form):
  available_from = forms.TimeField(
      widget=forms.TimeInput(attrs={'class': 'unbold-form'}, format='%H:%M'), 
      initial=time(0),
  )
  available_till = forms.TimeField(
      widget=forms.TimeInput(attrs={'class': 'unbold-form'}, format='%H:%M'), 
      initial=time(23,59,59),
  )
英文:

Add a format to the widget:

class SearchTimeSlotsForm(forms.Form):
  available_from = forms.TimeField(
      widget=forms.TimeInput(attrs={'class': 'unbold-form'}, format='%H:%M'), 
      initial=time(0),
  )
  available_till = forms.TimeField(
      widget=forms.TimeInput(attrs={'class': 'unbold-form'}, format='%H:%M'), 
      initial=time(23,59,59),
  )

huangapple
  • 本文由 发表于 2023年2月27日 01:54:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定