简体   繁体   中英

Django - converting datetime.date tuples

I'm trying to get some dates from my model.

In my queryset I get:

datetime.date(2019, 10, 15), datetime.date(2019, 10, 18), datetime.date(2019, 10, 2), datetime.date(2019, 9, 18), datetime.date(2019, 10, 28), datetime.date(2019, 10, 29)]

when querying the DB for my "reservation dates".

I need them to convert to normal dates,and if possibile,format them like this:

"19-10-2019"

So, dd-mm-yy format.

I created a monstrosity to do this for me, wich (kinda sometimes) works...I will show the monster just for lols.

here you go:

var unavailableDates = "{{ unavailable_dates }}"
        unavailableDates = unavailableDates.replace(/datetime.date/g, "").replace(/[{()}]/g, "").replace(/]/g, ' ').replace("[", ' ').split()
        var y = unavailableDates[0].match(/.{1,14}/g)
        var dates = []
        y.forEach((date, i) => {
            var now = moment(date).format('D-MM-YYYY')
            dates.push(now)
        })
        console.log(dates);
        function unavailable(date) {
            dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
            if ($.inArray(dmy, dates) == -1) {
                return [true, ""];
            } else {
                return [false, "", "Unavailable"];
            }
        }

        $(function () {
            $("#datepicker").datepicker({
                dateFormat: 'yy-mm-dd',
                beforeShowDay: unavailable
            })
        })

What would be the correct way of achieving what I want to do here? Thanks so much !

edit - my view:

def apartment_view(request, apartment_id):

    reservation = Reservation.objects.filter(apartment__pk=apartment_id)
    apartment = get_object_or_404(Apartment, pk=apartment_id)
    context = {'apartment': apartment, }
    unavailable_dates = apartment.reservations.values_list('start_date', 'end_date')

    form = ReservationForm()
    if request.method == 'GET':
        form = ReservationForm()

    elif request.method == 'POST':
        form = ReservationForm(request.POST)
        if form.is_valid():
            reservation = form.save(commit=False)
            reservation.apartment = apartment
            reservation.save()
            form.save()
            return HttpResponseRedirect('/booking/')
    args = {}
    args['form'] = form
    args['apartment'] = context
    args['reservation'] = reservation
    args['unavailable_dates'] = list(itertools.chain(*unavailable_dates))
    print(unavailable_dates)
    return render(request, 'booking/apartment.html', args)

You should use the appropriate data type to transfer information between Django and Javascript, which is JSON. In your view, you should convert the dates to strings in the relevant format, and then convert the data to JSON.

unavailable = [dt.strftime('%-d-%m-%Y') for dt in itertools.chain(*unavailable_dates)]
args['unavailable_dates'] = json.dumps(unavailable)

then in your JS you can do:

var dates = JSON.parse("{{ unavailable_dates|safe }}")

and there's no need to reformat them there.

Note however that your Django code does not give you all the unavailable dates; it just gives you the start and end date for each reservation. You probably want to do something like this to get all the unavailable dates:

unavailable = []
for start, end in apartment.reservations.values_list('start_date', 'end_date'):
    while start <= end:
        unavailable.append(start.strftime('%-d-%m-%Y'))
        start += datetime.timedelta(days=1)

args['unavailable_dates'] = json.dumps(unavailable)

This now gives you a flat list, consisting of all the dates between start and end inclusive for all the reservations for the apartment, properly formatted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM