Reputation: 2672
In a multilingual Django project, I want to display datefields in different formats, depending on the localization. Inspired by the example given in the Django documentation on Translation, I would like to use something like
def my_view(request, my_date):
output = _('Today is %(month)s %(day)s.') % {'month': my_date.month(),
'day': my_date.day()}
return HttpResponse(output)
where my_date
is a DateField
. Unfortunately, this object does not have day()
and month()
methods to extract the dates.
In a related question, one respondent suggests the babel module, but then I would have to specify the locale explicitly in the view, which seems like a bad idea to me.
What is the easiest way to present dates on multilingual Django sites?
Upvotes: 1
Views: 195
Reputation: 369074
DateField
is represented in Python by a datetime.date
instance.
datetime.date
objects have month
and day
attributes. (They are not methods.)
So you can write your view as:
def my_view(request, my_date):
output = _('Today is %(month)s %(day)s.') % {'month': my_date.month,
'day': my_date.day}
return HttpResponse(output)
Upvotes: 1