66 lines
2.7 KiB
Python
66 lines
2.7 KiB
Python
from django import forms
|
|
from django.db.models.query import QuerySet
|
|
from django.http import HttpRequest
|
|
from django.contrib import admin
|
|
from django.utils.safestring import SafeText
|
|
|
|
from ..models.instructors import Instructor
|
|
from ..models.availabilities import Availability
|
|
|
|
from datetime import date
|
|
from typing import Any, List
|
|
|
|
class AvailabilityForm(forms.ModelForm):
|
|
model=Availability
|
|
|
|
class AvailabilityAdmin(admin.ModelAdmin):
|
|
model = Availability
|
|
list_display = ("week", "instructor__surname", "instructor__name", "days_available", "hours")
|
|
list_filter = ("week", )
|
|
search_fields = ("instructor__surname","instructor__name", )
|
|
#actions = ("export", )
|
|
|
|
@admin.display(description="Days Available")
|
|
def days_available(self, obj: Availability) -> SafeText:
|
|
if not obj:
|
|
return SafeText("")
|
|
days: List[str | None] = [
|
|
"Mon" if obj.monday else None,
|
|
"Tue" if obj.tuesday else None,
|
|
"Wed" if obj.wednesday else None,
|
|
"Thu" if obj.thursday else None,
|
|
"Fri" if obj.friday else None,
|
|
"Sat" if obj.saturday else None,
|
|
"Sun" if obj.sunday else None,
|
|
]
|
|
return SafeText("/".join(d if d else "" for d in days))
|
|
|
|
def get_queryset(self, request: HttpRequest) -> QuerySet:
|
|
return super().get_queryset(request).order_by("-week", "instructor__surname", "instructor__name")
|
|
|
|
def get_form(self, request: HttpRequest, obj: Availability | None = None, change: bool = False, **kwargs: Any) -> AvailabilityForm:
|
|
form: AvailabilityForm = super().get_form(request, obj, change, **kwargs)
|
|
|
|
if change: # if is only a form change do not set default values and return form
|
|
return form
|
|
|
|
# If form contains the week field
|
|
current_week = date.today().isocalendar().week
|
|
if "week" in form.base_fields:
|
|
# Set default value as current week
|
|
form.base_fields["week"].initial = current_week
|
|
|
|
# If student is current user making request
|
|
if hasattr(request.user, "instructor"):
|
|
instructor: Instructor = request.user.instructor
|
|
if "instructor" in form.base_fields:
|
|
form.base_fields["instructor"].initial = instructor
|
|
form.base_fields["instructor"].disabled = True
|
|
return form
|
|
|
|
# Imposta automaticamente l'istruttore se non è già valorizzato
|
|
def save_model(self, request: HttpRequest, obj: Availability, form: AvailabilityForm, change: bool):
|
|
if hasattr(request.user, "instructor") and not obj.instructor_id:
|
|
obj.instructor = request.user.instructor
|
|
super().save_model(request, obj, form, change)
|
|
|