Django 模板中的 TimeField 格式
我正在 Django 中编写一个应用程序,并在模型中使用多个 TimeFields
。我只想使用时间格式 hh:mm (不是 hh:mm:ss 或 hh pm/am 或其他格式)。 我已经根据文档设置了 django 设置 TIME_FORMAT = 'H:i'
和 USE_L10N = False
,
如果设置为True
,
USE_L10N
会覆盖TIME_FORMAT
在我的模板中,我使用 Django 自动创建的输入框,例如:
{{formName.timeField}}
问题是,只要我引入类似“10:00”的内容并执行POST
,当POST
完成时,Django(或其他)将其转换为“10:00:00”(所以它添加了秒)。
- 有没有办法指定日期时间字段显示保存日期的格式?如果我可以在输入框的值中使用类似
|date:"H:i"
的内容就可以解决问题。
另一方面,我知道我可以手动输入框(不直接使用 {{formName.timeField}}
),但我过去遇到过一些问题,所以我想避免这种情况(至少暂时如此)。
没有秒的Django TimeField Model中也有类似的问题,但解决方案没有工作(它给我'NoneType
'对象没有属性'strptime
')
I'm writing an application in Django
and using several TimeFields
in a model. I only want to work with the time format hh:mm (not hh:mm:ss or hh p.m./a.m. or other things).
I have set the django setting TIME_FORMAT = 'H:i'
and USE_L10N = False
according to the documentation,
USE_L10N
overridesTIME_FORMAT
if set toTrue
In my template I'm using input boxes automatically created by Django like:
{{formName.timeField}}
The problem is that as long as I introduce something like "10:00" and do a POST
, when the POST
is done Django (or whatever) turns it into "10:00:00" (so it adds the seconds).
- Is there a way to specify the format in which datetime fields display saved dates? If I could just use something like
|date:"H:i"
in the value of the input box that would do the trick.
On the other side I know I could do the input box manually (not directly using {{formName.timeField}}
), but I've had some problems in the past with that so I would like to avoid that (at least for the moment).
There is also this similar question in Django TimeField Model without seconds, but the solution does not work (it gives me 'NoneType
' object has no attribute 'strptime
')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的应用程序中确实遇到了这个问题,并通过将
format
参数传递给 Django 的TimeInput
小部件来解决它:I had exactly this problem in my app, and solved it by passing a
format
parameter to Django'sTimeInput
widget:假设您希望所有
TimeFields
使用某种格式,则可以将TIME_INPUT_FORMATS
添加到您的设置文件中。例如,TIME_INPUT_FORMATS = ('%I:%M %p',)
会将您的时间格式设置为“5:30 PM”。文档: https://docs.djangoproject.com/en/dev/ref/设置/#std:设置-TIME_INPUT_FORMATS
Assuming you have a format you want all
TimeFields
to use, you can add theTIME_INPUT_FORMATS
to your settings file. For example,TIME_INPUT_FORMATS = ('%I:%M %p',)
will format your times as "5:30 PM".The docs: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TIME_INPUT_FORMATS