Skip to content

Commit

Permalink
Merge pull request #92 from Teknologforeningen/bugfix/timezone-instea…
Browse files Browse the repository at this point in the history
…d-of-datetime

Replaced usage of datetime with the Djangos own timezone. This resolv…
  • Loading branch information
filiptypjeu authored Aug 9, 2023
2 parents 5b39c1c + adc857d commit 4409fd8
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 38 deletions.
5 changes: 3 additions & 2 deletions fars/api/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

from django.utils import timezone
from django.utils.translation import gettext as _
from rest_framework import viewsets, generics, pagination
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters import rest_framework as filters
from booking.models import *
from api.serializers import *
from api.renderers import *
import datetime


class BookingFilter(filters.FilterSet):
Expand Down Expand Up @@ -53,7 +54,7 @@ class Meta:

# This class provides the view used by GeneriKey to get the list of bookings they need
class GeneriKeyBookingsList(viewsets.ViewSetMixin, generics.ListAPIView):
queryset = Booking.objects.filter(end__gt=datetime.datetime.now())
queryset = Booking.objects.filter(end__gt=timezone.now())
serializer_class = BookingSerializer
filter_class = GenerikeyBookingFilter
renderer_classes = (GeneriKeyBookingRenderer, )
Expand Down
23 changes: 13 additions & 10 deletions fars/booking/forms.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from django import forms
from booking.models import Booking, RepeatedBookingGroup
from django.contrib.auth.forms import AuthenticationForm
from django.forms.widgets import PasswordInput, TextInput, DateInput
from datetime import datetime, timedelta, date
from django.utils import timezone
from django.utils.translation import gettext as _
from booking.models import Booking, RepeatedBookingGroup


class DateTimeWidget(forms.widgets.MultiWidget):
Expand All @@ -28,7 +28,7 @@ def __init__(self, *args, **kwargs):
super(DateTimeField, self).__init__(list_fields, *args, **kwargs)

def compress(self, values):
return datetime.strptime("{}T{}".format(*values), "%Y-%m-%dT%H:%M:%S")
return timezone.datetime.strptime("{}T{}".format(*values), "%Y-%m-%dT%H:%M:%S")


class BookingForm(forms.ModelForm):
Expand All @@ -52,17 +52,20 @@ class Meta:
}

def clean_start(self):
start = self.cleaned_data['start']
start = timezone.make_aware(self.cleaned_data['start'])
now = timezone.now()
# If start is in the past, make it "now"
return datetime.now() if start < datetime.now() else start
return now if start < now else start

def clean_end(self):
return timezone.make_aware(self.cleaned_data['end'])

def clean(self):
cleaned_data = super().clean()
bookable = cleaned_data.get("bookable")
start = cleaned_data.get("start")
end = cleaned_data.get("end")
user = cleaned_data.get('user')
group = cleaned_data.get('booking_group')

# Check that user has permissions to book bookable
restriction_groups = bookable.booking_restriction_groups.all()
Expand All @@ -71,7 +74,7 @@ def clean(self):

if bookable and start and end:
# Check that booking does not violate bookable forward limit
if bookable.forward_limit_days > 0 and datetime.now() + timedelta(days=bookable.forward_limit_days) < end:
if bookable.forward_limit_days > 0 and timezone.now() + timezone.timedelta(days=bookable.forward_limit_days) < end:
raise forms.ValidationError(
_("{} may not be booked more than {} days in advance").format(bookable.name, bookable.forward_limit_days)
)
Expand Down Expand Up @@ -113,7 +116,7 @@ class CustomLoginForm(AuthenticationForm):

class RepeatingBookingForm(forms.Form):
frequency = forms.IntegerField(label=_('Frequency of repetitions (in days)'), initial=7)
repeat_until = forms.DateField(initial=date.today() + timedelta(days=365), widget=DateInput(attrs={'type': 'date'}))
repeat_until = forms.DateField(initial=timezone.now().date() + timezone.timedelta(days=365), widget=DateInput(attrs={'type': 'date'}))

# creates all bookings in a repeated booking
def save_repeating_booking_group(self, booking):
Expand All @@ -131,8 +134,8 @@ def save_repeating_booking_group(self, booking):
else:
booking.save()
booking.pk = None
booking.start += timedelta(days=data.get('frequency'))
booking.end += timedelta(days=data.get('frequency'))
booking.start += timezone.timedelta(days=data.get('frequency'))
booking.end += timezone.timedelta(days=data.get('frequency'))

return skipped_bookings

10 changes: 1 addition & 9 deletions fars/booking/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from django.contrib.auth.models import User, Group
from django.db.models import Q
from django.utils.translation import gettext as _
from datetime import timedelta, datetime

import logging

Expand Down Expand Up @@ -125,13 +124,6 @@ def get_time_slots(self):
return Timeslot.objects.filter(bookable=self)


def convert_time_to_closest_datetime(timestamp, datetimestamp):
# timestamp = time struct https://docs.python.org/3/library/time.html#time.struct_time
# datetimestamp = datetime object https://docs.python.org/3/library/datetime.html#datetime-objects
# This function returns a datetime object of the timeslot string regarding the received datetime object (dt)
# The converted datetime object has the same weekday, hour and minute as the time struct
return (datetimestamp + timedelta(timestamp.tm_wday - datetimestamp.weekday())).replace(hour=timestamp.tm_hour, minute=timestamp.tm_min)

class Timeslot(models.Model):

def __str__(self):
Expand Down Expand Up @@ -241,7 +233,7 @@ def __str__(self):
- the booking has ended.
'''
def is_unbookable_by_user(self, user):
if self.end < datetime.now(self.start.tzinfo):
if self.end < self.start:
return False, _("Bookings in the past may not be unbooked")
if self.bookable.is_user_admin(user) or user == self.user or self.booking_group in user.groups.all():
return True, ''
Expand Down
23 changes: 11 additions & 12 deletions fars/booking/views.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.http import HttpResponse, JsonResponse, HttpResponseForbidden
from django.utils import timezone
from django.utils.translation import gettext as _
from django.views import View
from booking.models import Booking, Bookable
from booking.forms import RepeatingBookingForm
from booking.metadata_forms import get_form_class
from datetime import datetime, timedelta
import dateutil.parser
from django.utils.translation import gettext as _
from django.views import View
import pytz
from fars.settings import TIME_ZONE
import json

def redirect_to_login(request):
Expand All @@ -35,14 +33,15 @@ def get(self, request):

starts = [x.start for x in all_bookings_by_user]
ends = [x.end for x in all_bookings_by_user]
timebooked = timedelta(
timebooked = timezone.timedelta(
seconds=sum([(y-x).total_seconds() for x, y in zip(starts, ends)])
)
timebooked_hours, reminder = divmod(timebooked.seconds, 3600)
stats[_('Total time booked')] = _('{hours} hours {minutes} minutes').format(hours=timebooked_hours + 24*timebooked.days, minutes=int(reminder/60))

future_bookings = all_bookings_by_user.filter(start__gt=datetime.now())
ongoing_bookings = all_bookings_by_user.filter(start__lt=datetime.now(), end__gt=datetime.now())
now = timezone.now()
future_bookings = all_bookings_by_user.filter(start__gt=now)
ongoing_bookings = all_bookings_by_user.filter(start__lt=now, end__gt=now)

return render(request, 'profile.html', {
'statistics': stats,
Expand Down Expand Up @@ -78,7 +77,7 @@ def get(self, request, bookable, year, month, day):
return HttpResponseForbidden()

return render(request, 'day.html', {
'date': datetime(year, month, day, 0, 0, 0, 0, pytz.timezone(TIME_ZONE)).isoformat(),
'date': timezone.datetime(year, month, day, 0, 0, 0, 0).isoformat(),
'bookable': bookable_obj,
'user': request.user
})
Expand All @@ -103,10 +102,10 @@ def dispatch(self, request, bookable):

def get(self, request, _):
booking = Booking()
booking.start = dateutil.parser.parse(request.GET['st']) if 'st' in request.GET else datetime.now()
booking.start = dateutil.parser.parse(request.GET['st']) if 'st' in request.GET else timezone.now()
# Remove the seconds and microseconds if they are present
booking.start = booking.start.replace(second=0, microsecond=0)
booking.end = dateutil.parser.parse(request.GET['et']) if 'et' in request.GET else booking.start + timedelta(hours=1)
booking.end = dateutil.parser.parse(request.GET['et']) if 'et' in request.GET else booking.start + timezone.timedelta(hours=1)
booking.bookable = self.context['bookable']

booking.user = request.user
Expand Down Expand Up @@ -177,7 +176,7 @@ def dispatch(self, request, booking_id):
def delete(self, request, _):
booking = self.context['booking']
if self.context['is_admin'] or self.context['unbookable']:
now = datetime.now(booking.start.tzinfo)
now = timezone.now()
removal_level = int(request.GET.get('repeat') or 0)
if self.context['is_admin'] and booking.repeatgroup and removal_level >= 1:
# Removal of a repeating booking. There are 3 different levels of removal
Expand Down
7 changes: 2 additions & 5 deletions fars/tabletpage/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from django.shortcuts import render
from django.views import View
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.utils import timezone
from booking.models import *
import pytz
from fars.settings import TIME_ZONE
from datetime import datetime


class TabletView(View):
template = 'tablet.html'
Expand All @@ -20,7 +17,7 @@ def dispatch(self, request, bookable):
return super().dispatch(request, bookable)

def get(self, request, bookable):
now = pytz.timezone(TIME_ZONE).localize(datetime.now())
now = timezone.now()
booking = Booking()
booking.bookable = self.context['bookable']
# self.context['bookform'] = BookingForm(instance=booking)
Expand Down

0 comments on commit 4409fd8

Please sign in to comment.