4242)
4343from user .models import User , TrainingType
4444from user .validators import validate_affiliation
45+ from django .forms import ModelMultipleChoiceField
4546
4647INVITATION_CHOICES = (
4748 (1 , 'Accept' ),
@@ -924,12 +925,25 @@ def __init__(self, *args, **kwargs):
924925 access_policy = self .access_policy
925926 )
926927
927- if self .access_policy not in {AccessPolicy .CREDENTIALED , AccessPolicy .CONTRIBUTOR_REVIEW }:
928+ if self .access_policy in {AccessPolicy .OPEN , AccessPolicy .RESTRICTED }:
928929 self .fields ['required_trainings' ].disabled = True
929930 self .fields ['required_trainings' ].required = False
930931 self .fields ['required_trainings' ].widget = forms .HiddenInput ()
931932 self .initial ['required_trainings' ] = ''
932933
934+ if self .access_policy == AccessPolicy .CREDENTIALED :
935+ self .fields ['required_trainings' ].disabled = False
936+ self .fields ['required_trainings' ].required = True
937+
938+ # Replace the original field with a custom version
939+ original_field = self .fields ['required_trainings' ]
940+ custom_field = CustomModelMultipleChoiceField (
941+ queryset = original_field .queryset .order_by ('name' ),
942+ required = True ,
943+ widget = original_field .widget
944+ )
945+ self .fields ['required_trainings' ] = custom_field
946+
933947 if self .access_policy == AccessPolicy .OPEN :
934948 self .fields ['dua' ].disabled = True
935949 self .fields ['dua' ].required = False
@@ -941,6 +955,26 @@ def __init__(self, *args, **kwargs):
941955 field .disabled = True
942956
943957
958+ class CustomModelMultipleChoiceField (ModelMultipleChoiceField ):
959+ def clean (self , value ):
960+ # If 'No training required' is explicitly selected, return an empty list
961+ if value == ['' ]:
962+ return []
963+
964+ # If no selection is made, raise a validation error
965+ if not value :
966+ raise forms .ValidationError ('Please select at least one training' )
967+
968+ return super ().clean (value )
969+
970+ def __init__ (self , * args , ** kwargs ):
971+ super ().__init__ (* args , ** kwargs )
972+ # Add empty option to the widget
973+ self .widget .choices = list (self .widget .choices )
974+ if ('' , 'No training required' ) not in self .widget .choices :
975+ self .widget .choices .append (('' , 'No training required' ))
976+
977+
944978class AuthorCommentsForm (forms .Form ):
945979 author_comments = forms .CharField (max_length = 12000 , required = False ,
946980 label = 'Comments for editor (optional)' ,
0 commit comments