Django:使用 L10N 将 DateTimeField 转换为字符串

Django: DateTimeField to string using L10N

使用 Django 模板标签,DateTimeField 将如下所示:

July 25, 2016, 7:11 a.m.

问题是,我的网站无限滚动并且新数据来自 AJAX,因此我不能为此使用 Django 的模板标签。使用它来获取日期:

str(self.date_created)

我得到这样的结果:

2016-07-23 14:10:01.531736+00:00

哪个看起来不太好...有什么方法可以使用 Django 的默认格式转换 DateTimeField 值吗?谢谢。

实际上,您仍然可以使用 Django 的内置 date 过滤器来获得 ajax 响应。在您的视图中使用 render_to_string 然后作为 json 发送(假设您的 js 期望 json)。

import json
from django.template.loader import render_to_string

class YourAjaxResponseView(View):
    template_name = 'your_ajax_response_template.html'

    # I ASSUMED IT'S A GET REQUEST
    def get(self, request, *args, **kwargs):
        data = dict()
        data["response"] = render_to_string(
           self.template_name,
           {
            "your_date": your_date
           },
           context_instance=RequestContext(request)
        )
       return HttpResponse(
         json.dumps(data),
         content_type="application/json",
         status=200
      )

你的模板可以是这个

 # your_ajax_response_template.html
 {{ your_date|date:"YOUR_FORMAT" }}

您可以在后端使用 self.date_created.strftime("%B %d, %Y, %I:%M %p") 格式化字段,也可以在前端格式化字段

var dateCreated = new Date(item.date_created);
dateCreated.toLocaleString()