dsite/timer/views.py

73 lines
2.2 KiB
Python

from django.contrib.auth.models import User, Group
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
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())
if form.is_valid():
form.save()
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