Coverage for website/education/forms.py: 73.17%

39 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2025-08-14 10:31 +0000

1import datetime 

2 

3from django.forms import ( 

4 CharField, 

5 ChoiceField, 

6 ModelChoiceField, 

7 ModelForm, 

8 TypedChoiceField, 

9) 

10from django.utils import timezone 

11from django.utils.translation import gettext_lazy as _ 

12 

13from utils.snippets import datetime_to_lectureyear 

14 

15from .models import Course, Exam, Summary 

16 

17 

18class AddExamForm(ModelForm): 

19 """Custom form to add exams, changes the possible years of the date.""" 

20 

21 this_year = datetime.date.today().year 

22 years = list(reversed(range(this_year - 8, this_year + 1))) 

23 

24 course = ModelChoiceField( 

25 queryset=Course.objects.order_by("name"), 

26 empty_label=None, 

27 ) 

28 type = ChoiceField(choices=Exam.EXAM_TYPES) 

29 

30 class Meta: 

31 model = Exam 

32 fields = ("file", "course", "type", "language", "exam_date") 

33 

34 def __init__(self, *args, **kwargs): 

35 super().__init__(*args, **kwargs) 

36 self.fields["exam_date"].widget.input_type = "date" 

37 

38 

39class AddSummaryForm(ModelForm): 

40 """Custom form to add summaries, orders courses by name and formats the year as lecture years.""" 

41 

42 course = ModelChoiceField( 

43 queryset=Course.objects.order_by("name"), 

44 empty_label=None, 

45 ) 

46 

47 this_year = datetime_to_lectureyear(timezone.now()) 

48 years = reversed( 

49 [(x, f"{x} - {x + 1}") for x in range(this_year - 20, this_year + 1)] 

50 ) 

51 

52 year = TypedChoiceField(choices=years, coerce=int, empty_value=this_year) 

53 

54 class Meta: 

55 model = Summary 

56 fields = ("name", "year", "language", "file", "course", "author") 

57 

58 

59class SummaryAdminForm(ModelForm): 

60 """Custom form for summaries so that we can show more data in the admin.""" 

61 

62 def __init__(self, data=None, files=None, **kwargs): 

63 super().__init__(data, files, **kwargs) 

64 obj = kwargs.get("instance", None) 

65 if not obj: 

66 self.fields["phone"].widget = self.fields["phone"].hidden_widget() 

67 self.fields["email"].widget = self.fields["email"].hidden_widget() 

68 else: 

69 self.fields["phone"].initial = obj.uploader.profile.phone_number 

70 self.fields["email"].initial = obj.uploader.email 

71 

72 phone = CharField(label=_("Uploader phone"), disabled=True, required=False) 

73 email = CharField(label=_("Uploader email"), disabled=True, required=False) 

74 

75 class Meta: 

76 model = Summary 

77 fields = "__all__"