django如何将日期格式化为DD/MM/YYYY [英] django how to format date to DD/MM/YYYY
问题描述
django在这种情况下如何将日期格式化为DD/MM/YYYY:
django how to format date to DD/MM/YYYY in this case :
class Invoice(models.Model):
date = models.DateField(default=timezone.now)
class InvoiceForm(ModelForm):
class Meta:
model = Invoice
fields = "__all__"
推荐答案
Model
并不关乎如何向客户展示数据,而是关乎如何在数据库中存储数据.
A Model
is not about how you present data to the customer, it is about how you store data in the database.
如果向用户显示数据,则取决于激活的设置.例如,如果 USE_L10N
设置[Django-doc] 处于活动状态,它将尝试确定用户的语言环境,并根据该格式设置日期.这意味着德国用户将看到与美国用户不同的日期格式.
If you present data to the user, it depends on the settings that are active. If for example USE_L10N
setting [Django-doc] is active, it will try to determine the locale of the user, and based on that format the date. This means that a German user will see a different date format than an American user for example.
If USE_L10N
is set to False
, the form field with use the first item in the DATE_INPUT_FORMATS
setting [Django-doc]. By default this is:
[
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ]
因此它将首先格式化年,月,然后格式化日期,例如 2020-08-28
.因此,您可以为第一个具有 DateField
字段[Django-doc] .
so it will first format the year, month and then date, so 2020-08-28
for example. You thus can specify a different element (first) to change this for all Form
s that have DateField
fields [Django-doc].
如果要指定一次性字段,则可以使用 DateInput 小部件的 format =…
参数[Django-doc] :
If you want to specify a one-off field, you can use the format=…
parameter [Django-doc] of the DateInput
widget for example:
from django import forms
class InvoiceForm(ModelForm):
date = forms.DateField(widget=forms.DateInput(format='%d/%m%Y'))
class Meta:
model = Invoice
fields = '__all__'
然后,您还应该在 DATE_INPUT_FORMATS
设置中包括该格式,并且优先级比重叠"更好.%m/%d/%Y
和%m/%d/%y
之类的格式,以确保也可以解析该值.
Then you should also include the format in the DATE_INPUT_FORMATS
setting, and better with a higher priority than "overlapping" formats like %m/%d/%Y
and %m/%d/%y
, to ensure that the value can also be parsed.
您还可以通过指定 查看全文