Django MultiValueField and MultiWidget ChoiceField custom choices

I am trying to create a form that allows students to request courses, and I have been working on the time selection field, I would like the field to select a day of the week and a time of the day, but the hours of each course is different, so I would like to provide the available times in the form of the course instead of the field definition, this is what I tried:

class ClassTimeWidgit(forms.MultiWidget):
    def __init__(self, time, attrs=None) -> None:
        widgets = [
            forms.Select(choices=[
                ('Monday', 'Monday'),
                ('Tuesday', 'Tuesday'),
                ('Wednesday', 'Wednesday'),
                ('Thursday', 'Thursday'),
                ('Friday', 'Friday'),
                ('Saturday', 'Saturday'),
                ('Sunday', 'Sunday'),
            ], attrs={'style':'width:130px'}),
            forms.Select(choices=time, attrs={'style':'width:130px'})
        ]
        super(ClassTimeWidgit, self).__init__(widgets, attrs)
    
    def decompress(self, value):
        if value:
            return value.split(' ')
        return ['', '']

class ClassTimeField(forms.MultiValueField):
    widget = ClassTimeWidgit

    def __init__(self, time, **kwargs) -> None:
        f = (
            forms.ChoiceField(choices=[
                    ('Monday', 'Monday'),
                    ('Tuesday', 'Tuesday'),
                    ('Wednesday', 'Wednesday'),
                    ('Thursday', 'Thursday'),
                    ('Friday', 'Friday'),
                    ('Saturday', 'Saturday'),
                    ('Sunday', 'Sunday'),
                ]
            ),
            forms.ChoiceField(choices=time)
        )
        super().__init__(fields=f, require_all_fields=True, **kwargs)
    
    def compress(self, data_list):
        return ' '.join(data_list)



class RequestCourseForm(forms.ModelForm):
    teacher = forms.ModelChoiceField(queryset=User.objects.filter(profile__teacher_status=True))
    class_count = forms.IntegerField(widget=forms.Select(choices=[(10,10), (20,20)]))
    class_time = ClassTimeField(time=[(f'{i}:00', f'{i}:00') for i in range(8,21)])

    class Meta:
        model = Request
        fields = ['teacher', 'class_count', 'class_time']

I am trying to make it so I can set the available times in the form like how the forms.ChoiceField works. Thank you so much for your help.

Back to Top