Models.py date format conversion

Hello everyone,
I am facing a problem with my models.py in relation to a date return which is of the type for example 07 January 2025 19:20 that I must use to perform a search filter with daterangepicker here is part of my model for the table Stock

from django.db import models
from django.utils import timezone

class Stock(models.Model):
    product = models.ForeignKey(Produit, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0)
    type = models.CharField(max_length=2,choices=(('1','Entrée'),('2','Sortie')), default = 1)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)
     
     
    def __str__(self):
        return self.product.ref_produit + ' - ' + self.product.designation

Remember that my daterangepicker is in the format: “DD/MM/YYYY.
This incompatibility means that I can’t perform a search operation.
Here’s part of my settings.py :

# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'UTC

USE_I18N = True

USE_TZ = True

Here’s my javascript code

//filtering data 
var start_date = moment().startOf("month");
var end_date = moment().endOf("month");
var DateFilterFunction = (function (oSettings, aData, iDataIndex) {
   var dateStart = parseDateValue(start_date);
   var dateEnd = parseDateValue(end_date);
   
   //Date/Heure = 1
   //Quantité = 2
   //Type = 3
   //Action = 4
   var evalDate= parseDateValue(aData[1]);
     if ( ( isNaN( dateStart ) && isNaN( dateEnd ) ) ||
          ( isNaN( dateStart ) && evalDate <= dateEnd ) ||
          ( dateStart <= evalDate && isNaN( dateEnd ) ) ||
          ( dateStart <= evalDate && evalDate <= dateEnd ) )
     {
         return true;
     }
     return false;
});

// converting format dd/mm/yyyy format javascript 
//  var parsedDate= new Date(dateArray[2], parseInt(dateArray[1])-1, dateArray[0]);
function parseDateValue(rawDate) {
   var dateArray= rawDate.split("/");
   var parsedDate= new Date(dateArray[2], parseInt(dateArray[1])-1, dateArray[0]);  // -1 because months are from 0 to 11   
   return parsedDate;
}    

$( document ).ready(function() {
//div class dateseacrhbox dom input daterangepicker
var $dTable = $('#stock-list').DataTable({
 "dom": "<'row'<'col-sm-4'l><'col-sm-5' <'datesearchbox'>><'col-sm-3'f>>" + 'B' +
   "<'row'<'col-sm-12'tr>>" + 
   "<'row'<'col-sm-5'i><'col-sm-7'p>>",
   buttons: ['csv', 'excel', 'pdf', 'print'],

   initComplete: function (settings, json) {
    $('table td, table th').addClass('px-2 py-1')
},
drawCallback: function (settings) {
    $('table td, table th').addClass('px-2 py-1')
},
language: {
    "emptyTable": "Aucun élément trouvé",
    "info": "Affichage de l'élement _START_ à _END_ sur _TOTAL_ éléments",
    "sLengthMenu": "Afficher _MENU_ éléments",
    "infoEmpty": "Affichage de 0 à 0 sur 0 entrées",
    "infoFiltered": "(filtrées depuis un total de _MAX_ entrées)",
    "loadingRecords": "Chargement...",
    "processing": "En cours...",
    "search": "Rechercher",
    "zeroRecords": "L'élément recherché n'existe pas",
    "oPaginate": {
        "sFirst": "Premier",
        "sPrevious": "Précédent",
        "sNext": "Suivant",
        "sLast": "Dernier"
    }

},

"aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "Tout"]],
"iDisplayLength": 3,
"bFilter": true


});
  

//$("div.datesearchbox").html('<div class="input-group"> <div class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </div><input type="text" size="30"  class="form-control pull-right" id="datesearch" placeholder="Recherche par plage de date.."> </div>');


$("div.datesearchbox").html('<div class="input-group mb-3"><span class="input-group-text" id="basic-addon1"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-calendar" viewBox="0 0 16 16"><path d="M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5M1 4v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V4z"/></svg></span><input type="text" class="form-control" id="datesearch" placeholder="Recherche par plage de date.." aria-label="Username" aria-describedby="basic-addon1"></div>');

//document.getElementsByClassName("datesearchbox")[0].style.textAlign = "right";

//daterangepicker input id datesearch



$('#datesearch').daterangepicker({
  autoUpdateInput: false,

   locale: {

      applyLabel: 'Appliquer',
      cancelLabel: 'Annuler',
      customRangeLabel: 'Période personnalisée',
      daysOfWeek: moment().lang()._weekdaysMin,
      monthNames: moment().lang()._months,
      "daysOfWeek": [
          "Dim",
          "Lun",
          "Mar",
          "Mer",
          "Jeu",
          "Ven",
          "Sam"
      ],
      "monthNames": [
          "Janvier",
          "Février",
          "Mars",
          "Avril",
          "Mai",
          "Juin",
          "Juillet",
          "Août",
          "Septembre",
          "Octobre",
          "Novembre",
          "Décembre"
      ],

      firstDay: 0

  },
  ranges: {
      'Aujourd\'hui': [moment(), moment()],
      'Hier': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
      '7 jours précédents': [moment().subtract(7, 'days'), moment()],
      '30 derniers jours': [moment().subtract(30, 'days'), moment()],
      'Ce mois': [moment().startOf('month'), moment().endOf('month')],
      'Mois précedent': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
  },
  opens: "right",
  format: "DD/MM/YYYY",
},

function(start, end, label) {
  // Parse it to a moment
  var s = moment(start.toISOString());
  var e = moment(end.toISOString());
  startdate = s.format("DD-MM-YYYY");
  enddate = e.format("DD-MM-YYYY");
 }
);

//process apply date range
 $('#datesearch').on('apply.daterangepicker', function(ev, picker) {
    $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
    start_date=picker.startDate.format('DD/MM/YYYY');
    end_date=picker.endDate.format('DD/MM/YYYY');
    $.fn.dataTableExt.afnFiltering.push(DateFilterFunction);
    $dTable.draw();
 });

 $('#datesearch').on('cancel.daterangepicker', function(ev, picker) {
   $(this).val('');
   start_date='';
   end_date='';
   $.fn.dataTable.ext.search.splice($.fn.dataTable.ext.search.indexOf(DateFilterFunction, 1));
   $dTable.draw();
 });
});

I would like to change the format of my date template to e.g. 07-01-2025 19:20
Thank you

Can you share the code for this search operation that you’ve been trying to use along with the error? I think there’s a view and form that we’re missing that will be the key to the solution.

Here’s my view

{% extends 'production/base.html' %}
{% load humanize %}

{% block title %} Stock {% endblock %}

{% block content %}

<!-- page content -->
<div class="right_col" role="main">

    {% include '_messages.html' %}  


    <div class="card card-default border shadow rounded-0">
        <div class="card-header">
            <div class="w-100 d-flex justify-content-between">
                <h5 class="fw-bolder card-title">Historique des entrées/ sorties</h5>
                <button class="btn btn-primary btn-sm rounded-0 bg-gradient px-3" type="button" id="add_stock"><i class="fa fa-plus"></i> Ajouter Stock</button>
            </div>
        </div>
        <div class="card-body">
            <div class="conteiner-fluid">
                <fieldset class="border-bottom">
                    <legend>Fiche des Mouvements</legend>
                    <dl>
                        <dt class="tex-muted">Références</dt>
                        <dd class="ps-4">{{ product.ref_produit }}</dd>
                        <dt class="tex-muted">Noms</dt>
                        <dd class="ps-4">{{ product.designation }}</dd>
                        <dt class="tex-muted">Prix de vente unitaire</dt>
                        <dd class="ps-4">{{ product.prix_vente|intcomma }}</dd>
                    </dl>
                </fieldset>
                <fieldset>
                    <legend>Détails de l'Historique</legend>
                    <table class="table table-bordered" id="stock-list">
                        <colgroup>
                            <col width="5%">
                            <col width="25%">
                            <col width="25%">
                            <col width="25%">
                            <col width="20%">
                        </colgroup>
                        <thead>
                            <th class="text-center">#</th>
                            <th class="text-center">Date/Heure</th>
                            <th class="text-center">Quantités</th>
                            <th class="text-center">Type</th>
                            <th class="text-center">Action</th>
                        </thead>
                        <tbody>
                            {% for stock in stocks %}
                            <tr>
                                <td class="text-center">{{ forloop.counter }}</td>
                                <td class="">{{ stock.date_created }}</td>
                                <td class="text-center">{{ stock.quantity }}</td>
                                <td class="text-center">
                                    {% if stock.type == '1' %}
                                    <span class="badge px-3 rounded-pill bg-primary bg-gradient">Entrée</span> {% else %}
                                    <span class="badge px-3 rounded-pill bg-danger bg-gradient">Sortie</span> {% endif %}
                                </td>
                                <td class="text-center">
                                    {% if stock.type == '1' %}
                                    <a class="btn btn-outline-primary btn-sm edit-data" href="javascript:void(0)" data-id="{{ stock.pk }}" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <button class="btn btn-outline-danger btn-sm delete-data" type="button" data-id="{{ stock.pk }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                    {% else %}
                                    ------
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </fieldset>
            </div>
        </div>
    </div>


</div>

<!-- /page content -->


{% endblock %}

{% block ScriptBlock %}
<script>

    $(function () {
        $('#add_stock').click(function() {
            uni_modal("<i class='fa fa-plus'></i> Ajout du Stock : <b>{{ product }}</b>", '{% url "manage-stock" product.pk %}')
        })
        $('.edit-data').click(function() {
            uni_modal("<i class='fa fa-edit'></i> Modifier Stock", '{% url "manage-stock" product.pk %}/' + $(this).attr('data-id'))
        })

        $('.delete-data').click(function() {
            _conf("Cette action entrainera la suppression de la quantité de votre Stock", 'delete_stock', [$(this).attr('data-id')])
        })
       
       
    })

    function delete_stock($id) {
        start_loader();
        var _this = $(this)
        $('.err-msg').remove();
        var el = $('<div>')
        el.addClass("alert alert-danger err-msg")
        el.hide()
        $.ajax({
            url: '{% url "delete-stock" %}',
            headers: {
                'X-CSRFToken': "{{csrf_token}}"
            },
            method: 'POST',
            data: {
                id: $id
            },
            dataType: 'json',
            error: err => {
                console.log(err)
                el.text('An error occurred.')
                el.show('slow')
                end_loader()
            },
            success: function(resp) {
                if (resp.status == 'success') {
                    location.reload()
                } else if (!!resp.msg) {
                    el.text('An error occurred.')
                    el.show('slow')
                } else {
                    el.text('An error occurred.')
                    el.show('slow')
                }
                end_loader()
            }
        })
    }

    
</script>

{% endblock ScriptBlock %}

The search filter dedicated to the date is located in my dataTable and this has been specified in my javascript code

That’s not a view. That’s a template with some embedded JavaScript.

The view is going to be the Python code that receives the request and returns a response.

my problem is with the return date of my model, which I explained above, because it sends me back to my admin panel and displays this screenshot

Here’s a screenshot of my database

Have you considered doing something like <td data-date="{{stock.date_created|date:'SHORT_DATETIME_FORMAT'}}"> (this assumes the data table can read from the attribute, this may take some extra JS).

You would also need to change your SHORT_DATETIME_FORMAT setting.

You could avoid changing the setting and use |date:"your format here" as per the formatting rules

I haven’t considered this method. After applying your recommendation, the display of the date format is perfect now indeed you are right about the revision of my javascript code.
Thank you very much Mrs CodenameTim.