I am building a web app that needs i18n support. It dispays dates and times in templates as well as via Ajax calls.
I have USE_I18N and USE_L10N set to True and 'django.middleware.locale.LocaleMiddleware' installed. In my template when I do value|date on a queryset passed in context it is corr开发者_JS百科ectly formatted to browser locale. When I serialize the output of my model it is not. I have read all the doc and can't see how to do it.
Basically I have a model with a DateTimeField. I am trying to return it to Javascript via Ajax in a localized format. I am using serialize to return it but the date time is not formatted to locale.
See below:
Model:
class Messages(models.Model):
message = models.CharField(max_length=500)
date_created = models.DateTimeField(auto_now_add=True)
thread_id = models.IntegerField(db_index=True)
Web Service View:
def get_message_thread(request):
message_thread = request.POST['message_thread']
message_threads = Messages.objects.filter(thread_id=message_thread)
from django.core.serializers import serialize
json = serialize("json", message_threads, fields=('id', 'message' 'date_created'))
return HttpResponse(json, 'content-type:javascript/json')
Does anyone have anty ideas on what I need to do to make a correctly locale formatted date time accessible to my javascript for display in my page?
Many thanks
Rich
You'll need to rething serialization but basic idea is as fallows:
from django.utils import formats
date_format = formats.get_format('DATE_FORMAT')
serialized_date = date.strftime(date_format)
More info can be found at django-documentation: Date format helper functions
精彩评论