Skip to content
Advertisement

Create Array from Model Data in Django Template in

I am trying to use JQuery date picker and I want to make use of the beforeShowDay method in order to block out dates in the date picker. I have been able to get the widget to work and if I define an array, the beforeShowDay method works flawlessly. But my issue is passing the data from my Django model to create an array. Is there a way to create an array within the element in the template in order to achieve this?

template

 <script>
            # works as intended when the array is defined manually
            var array = [
              "2022-10-01"
            ]

            # this is where I am having trouble creating an array from the model data
            var array = [
              {% for x in listing_reservations %}
                {{x.dates}}
              {% endfor %}
            ]

            $(function() {
              $( "#id_start_date" ).datepicker(
                {
                  beforeShowDay: function(date){
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                    return [ array.indexOf(string) == -1 ];
                }
                }
              );
            });
</script>

Advertisement

Answer

Finally figured it out, hopefully helps someone in the future! Thanks Haduki for the help :)

          <script>

            var array = [];

            {% for x in reservations %}
              var date = new Date("{{x.isoformat}}").toISOString().split('T')[0];
              array.push(date);
            {% endfor %}

            console.info(array)

            $(function() {
              $( "#id_start_date" ).datepicker(
                {
                  beforeShowDay: function(date){
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                    return [ array.indexOf(string) == -1 ];
                }
                }
              );
            });

          </script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement