from django.contrib.auth.models import User, Group import django.forms from django.shortcuts import render import django.views.generic from rest_framework import authentication, permissions, status, viewsets from rest_framework.generics import CreateAPIView from rest_framework.response import Response from rest_framework.views import APIView from django.http import JsonResponse import timer.serializers import timer.models import timer.forms import datetime from django.utils.timezone import localtime from django.urls import reverse class OfficeHoursAPI(CreateAPIView): authentication_classes = ( authentication.TokenAuthentication, authentication.SessionAuthentication, authentication.BasicAuthentication, ) permission_classes = (permissions.IsAuthenticated,) queryset = timer.models.OfficeHours.objects.all() def create(self, request, *args, **kwargs): begins_at = request.data.get('begins_at') if not begins_at: raise try: begins_at = timer.models.OfficeHours.parse_time_str(begins_at) ends_at = timer.models.OfficeHours.get_ends_at(begins_at) oh, __ = timer.models.OfficeHours.objects.get_or_create( begins_at=begins_at, ends_at=ends_at, user=request.user ) except ValueError: raise oh.refresh_from_db() resp_data = {'begins_at': oh.get_begins_at_str, 'ends_at': oh.get_ends_at_str} return Response(resp_data, status=status.HTTP_201_CREATED) class OfficeHoursFormView(django.views.generic.FormView): template_name = 'index.html' form_class = timer.forms.OfficeHoursForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs def post(self, request, *args, **kwargs): form = self.form_class(**self.get_form_kwargs()) try: form.is_valid() form.save() except django.forms.ValidationError as e: return JsonResponse({'error': e.message}, status=status.HTTP_400_BAD_REQUEST) return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('office-hours-page') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today_oh = timer.models.OfficeHours.objects.filter(begins_at__date=localtime().date()).last() context['today_oh'] = today_oh return context