from django.shortcuts import render, redirect from django.views.generic.list import ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.forms.models import model_to_dict from .models import Schedule from .forms import ScheduleForm import json # Create your views here. class ScheduleListView(LoginRequiredMixin,ListView): """ This view will give a list of all entered schedules. The list is filtered on the logged in employee. Only the schedules owned by the logged in user are shown. The results are shown with 10 items per page. A pager will be shown when there are more then 10 schedules """ model = Schedule paginate_by = 10 def get_queryset(self): return Schedule.objects.filter(employee=self.request.user.employee).order_by('-created_at') @login_required def new_or_update_schedule(request, schedule_id = None): """ This view will create or update an existing schedule. At the moment there is not a real update, but a clone functionality. So every schedule that is updated will be stored as a new schedule. Only schedules owned by the logged in user can be loaded here and can be cloned. The data of the form is stored as a JSON object in a single database field for more flexibility. Arguments: request HttpRequest -- This is the HTTP request from the Django framework. This will hold the current logged in user info. Keyword Arguments: schedule_id Schedule -- This is the schedule to be edited. When none, a new schedule will be created (default: {None}) Returns: A view with an empty form to create a new schedule or a prefilled form for cloning. """ template_name = 'schedule/schedule_new.html' schedule = None if schedule_id is not None: try: schedule = Schedule.objects.get(pk=schedule_id,employee=request.user.employee) except Schedule.DoesNotExist: pass if request.method == 'POST': schedule_form = ScheduleForm(request.POST) if schedule_form.is_valid(): new_schedule = Schedule() try: new_schedule.planning_source = json.loads(schedule_form.cleaned_data['json']) except json.JSONDecodeError as ex: new_schedule.planning_source = json.loads(json.dumps({'error': str(ex)})) new_schedule.status = Schedule.ScheduleStatus.INVALID new_schedule.employee = request.user.employee new_schedule.name = schedule_form.cleaned_data['name'] new_schedule.email = schedule_form.cleaned_data['email'] new_schedule.save() return redirect('schedule:list') else: if schedule is not None: schedule = json.dumps(schedule.planning_source) schedule_form = ScheduleForm(initial={'json' : schedule}) return render(request, template_name, { 'form' : schedule_form, })