Coverage for website/documents/forms.py: 78.00%

48 statements  

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

1from django import forms 

2from django.contrib import admin 

3from django.forms import widgets 

4from django.utils import timezone 

5 

6from documents import models 

7from utils.snippets import datetime_to_lectureyear 

8 

9 

10class DocumentFileInput(widgets.ClearableFileInput): 

11 """Wrapper around Django's :class:`~django.forms.widgets.ClearableFileInput`. 

12 

13 It overrides the URL of the associated file when it is fetched. 

14 """ 

15 

16 template_name = "widgets/clearable_file_input.html" 

17 

18 def get_context(self, name, value, attrs): 

19 context = super().get_context(name, value, attrs) 

20 if hasattr(value, "url"): 

21 doc = models.Document.objects.get(file=value) 

22 context["document_id"] = doc.pk 

23 context["language"] = "en" 

24 return context 

25 

26 

27class MinutesForm(forms.ModelForm): 

28 """Form that overrides the widgets for the files.""" 

29 

30 class Meta: 

31 model = models.Minutes 

32 fields = ( 

33 "file", 

34 "members_only", 

35 ) 

36 widgets = { 

37 "file": DocumentFileInput, 

38 } 

39 

40 

41class AnnualDocumentForm(forms.ModelForm): 

42 """Form that provides custom functionality for annual documents.""" 

43 

44 class Meta: 

45 model = models.AnnualDocument 

46 fields = "__all__" 

47 widgets = { 

48 "year": forms.Select, 

49 "file": DocumentFileInput, 

50 } 

51 

52 @staticmethod 

53 def _current_year(): 

54 """Get the current lecture year.""" 

55 return datetime_to_lectureyear(timezone.now()) 

56 

57 @staticmethod 

58 def _year_choices(): 

59 """Get the lecture years.""" 

60 current = datetime_to_lectureyear(timezone.now()) 

61 return [(year, f"{year}-{year + 1}") for year in range(current + 1, 1989, -1)] 

62 

63 year = forms.TypedChoiceField( 

64 coerce=int, choices=_year_choices.__func__, initial=_current_year.__func__ 

65 ) 

66 

67 

68class AssociationDocumentForm(forms.ModelForm): 

69 """Form that overrides the widgets for the files.""" 

70 

71 class Meta: 

72 model = models.AssociationDocument 

73 fields = ( 

74 "name", 

75 "file", 

76 "members_only", 

77 ) 

78 widgets = { 

79 "file": DocumentFileInput, 

80 } 

81 

82 

83class MiscellaneousDocumentForm(forms.ModelForm): 

84 """Form that overrides the widgets for the files.""" 

85 

86 class Meta: 

87 model = models.MiscellaneousDocument 

88 fields = ( 

89 "name", 

90 "file", 

91 "members_only", 

92 ) 

93 widgets = { 

94 "file": DocumentFileInput, 

95 } 

96 

97 

98class GeneralMeetingForm(forms.ModelForm): 

99 """Custom form for general meetings with a custom widget for documents.""" 

100 

101 class Meta: 

102 model = models.GeneralMeeting 

103 fields = "__all__" 

104 widgets = { 

105 "documents": admin.widgets.FilteredSelectMultiple( 

106 "documents", is_stacked=False 

107 ) 

108 }