Antoni4040
Antoni4040

Reputation: 2319

Django: DateTimeField to string using L10N

Using the Django template tags, a DateTimeField will look like this:

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

Problem is, my website has an infinite scroll and new data come through AJAX, and so I can't use Django's template tags for that. Using this to get the date:

str(self.date_created)

I get something like this:

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

Which doesn't look good... Is there any way to convert the DateTimeField value using Django's default format? Thank you.

Upvotes: 1

Views: 2537

Answers (2)

Tiny Instance
Tiny Instance

Reputation: 2671

Actually you can still use Django's built in date filter for an ajax response. Inside your view utilise the render_to_string then send as json (assuming your js expects 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
      )

And your template can simply be this

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

Upvotes: 2

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7787

You can format field on backend with self.date_created.strftime("%B %d, %Y, %I:%M %p") or you can format it on frontend

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

Upvotes: 3

Related Questions