How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?

Question:

models.py

class Log(models.Model):
    source = models.CharField(max_length=1000, default='')
    date = models.DateTimeField(default=datetime.now, blank = True)

views.py

The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse.

def backlog_list(request): 
    account_name = request.POST['account_name']
    access_log = Log.objects.filter(source=account_name)
    return JsonResponse({"access_log":list(access_log.values())})

dashboard.html

This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like this otherwise.

<h3>You scanned the QR code during these times.</h3>
<div id="display">
    
</div>

<script>
    $(document).ready(function(){
    
    setInterval(function(){
        $.ajax({
            type: 'POST',
            url : "/backlog_list",
            data:{
                  account_name:$('#account_name').val(),
                  csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                },
            success: function(response){
                console.log(response);
                $("#display").empty();
                for (var key in response.access_log)
                {
                    var temp="<div class='container darker'><span class='time-left'>"+response.access_log[key].date+"</span></div>";
                    $("#display").append(temp);
                }
            },
            error: function(response){
                alert('An error occurred')
            }
        });
    },1000);
    })
</script>

My goal is to have the Date and time displayed like "Jan. 10, 2000, 9:30:20 A.M."

I’ve tried changing the format directly from the models.py by adding "strftime" but the error response is triggered.

Asked By: ARKONITE Requiem

||

Answers:

You’re trying to format the date in the HTML by appending it to a string. Unfortunately, this won’t work because the date value will be treated as a string and not as a date object.

To format the date in the desired way, you will need to convert it to a date object in JavaScript and then use a date formatting function to convert it to the desired string format.

Here is an example of how you could do this:

// Parse the date value from the response into a date object
var date = new Date(response.access_log[key].date);

// Use the toLocaleDateString() function to format the date as "Jan. 10, 2000"
var dateString = date.toLocaleDateString('en-US', {
  month: 'short',
  day: 'numeric',
  year: 'numeric'
});

// Use the toLocaleTimeString() function to format the time as "9:30:20 A.M."
var timeString = date.toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true
});

// Append the formatted date and time to the HTML
var temp="<div class='container darker'><span class='time-left'>" + dateString + ", " + timeString + "</span></div>";
$("#display").append(temp);

You can read more about the toLocaleDateString() and toLocaleTimeString() functions in the JavaScript documentation:

Answered By: Tharun K

One way to set the format you need is via Javascript, Tharun posted an example in his answer.

Alternatively, you can specify the format you need in views.py:

def backlog_list(request): 
    ...
    dates = [
        val.strftime('%b. %d, %Y, %I:%M:%S %p') 
        for val in access_log.values_list("date", flat=True)
    ]
    return JsonResponse({"access_log":[{"date": d} for d in dates]})

Format string reference – https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Answered By: Eugene Prikazchikov
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.