Django Ajax response date and time format
<p>Got a problem... </p>

<p>I use <code>Django</code>, <code>SQLite</code>, <code>jquery</code> and <code>AJAX</code>.</p>

<p>The problem is that when I get date and time from my database, it looks weird.</p>

<p>Is there any way to display it normally, as <code>dd/mm/yyyy HH:MM</code> ?</p>

<p><strong>Modeles.py</strong></p>

<pre><code>class QueryHistory(models.Model) :
 userID = models.CharField(max_length=100)
 date = models.DateTimeField(auto_now_add=True, blank=True)
</code></pre>

<p><strong>View.py</strong></p>

<pre><code>queries_list = serializers.serialize(
             'json',
             (QueryHistory.objects.filter(
                 userID = request.session['user_id']
               ).order_by('-id')[:5])
           )
return HttpResponse(json.dumps(queries_list), content_type="application/json")
</code></pre>

<p><strong>Js.js</strong></p>

<pre><code>success : function(response) {
 var queries_list = jQuery.parseJSON(response);
 console.log(response);
}
</code></pre>

<blockquote>
  <p><strong>Result:</strong> 2016-09-21T06:43:26.693Z</p>
  
  <p><strong>Should be:</strong> 21/09/2016 06:43</p>
</blockquote>

<p>It's not weird, it's ISO 8601 and it's not a good idea to change it. But you can by defining your own encoder:</p>

<pre><code>import json
from datetime import dateteime

from django.forms.models import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder

class MyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, date):
            return obj.strftime('%d.%m.%Y')
        return super(MyEncoder, self).default(obj)


json.dumps([model_to_dict(o) for o in QueryHistory.objects.all()], cls=MyEncoder)
</code></pre>

<p>Or by your own serializer:</p>

<pre><code>import json
from datetime import dateteime

from django.core.serializers.python import Serializer

class MySerializer(Serializer):
    def handle_field(self, obj, field):
        value = field.value_from_object(obj)
        if isinstance(value, date):
            self._current['date'] = value.strftime('%d.%m.%Y')
        else:
            super(MySerializer, self).handle_field(obj, field)


serializer = MySerializer()
queries_list = serializer.serialize(QueryHistory.objects.all())
json.dumps(queries_list)
</code></pre>

jquery python ajax django response