简体   繁体   中英

ModelChoiceField in ModelFormSet not selecting initial value when using custom ModelForm

So I am using a ModelFormSet to show a list of forms based on a predefined ModelForm . I need to customize the two fields in the forms, and therefore I have created this ModelForm :

# forms.py

class StudentRelationshipForm(forms.ModelForm):

    # the row below causes the issue:
    classroom = forms.ModelChoiceField(queryset=Classroom.objects.all(), widget=forms.Select(attrs={'class':'form-control border-0 bg-white text-black h5'}), to_field_name='clarsroom_name', disabled=True, required=True)

    student_type = forms.ChoiceField(choices=StudentRelatuionship.STUDENT_TYPES, widget=forms.Select(attrs={'class': 'form-control'}), required=True)
    class Meta:
        model = StudentRelatuionship
        fields = [
            'classroom',
            'student_type',
        ]

I am creating the ModelFormSet in the following view:

# views.py

class MyView(DetailView):

     def get_context_data(self, **kwargs):

             classroom_list = [ a list of classrooms goes here ]
             initial_formset_data = []
             for classroom in related_companies:
                 initial_formset_data.append({'classroom': classroom.pk})

             StudentRelationshipFormSet = modelformset_factory(StudenrRelatuionship, form=StudentRelatuionshipForm, fields=['classroom', 'student_type'], extra=formset_extras)
             context['investor_relationships_formset'] = StudentRelationshipFormSet(queryset=StudentRelatuionship.objects.filter(student=self.request.user.user_profile, classroom__in=classroom_list), initial=initial_formset_data)

Basically the problem that I have is that when I specify the classroom field in StudentRelationshipForm in forms.py , the HTML Select widget's default value becomes --------- . However, if I remove the row from forms.py, the HTML select widget correctly selects the classroom name from the database when editing an existing instance.

How could I overcome this? The reason why I need the row is to specify that the field should be disabled. If there is another way to achieve this, please tell me.

PS: I need the disabled=True in the form, and not in the template, because the disabled=True prevents the user from sending a different input than the initial one even if they change the HTML source.

I managed to resolve the issue by specifying the attributes of the field in the __init__ of the Form :


class StudentRelationshipForm(forms.ModelForm):

...

    def __init__(self, *args, **kwargs):
        super(StudentRelationshipForm, self).__init__(*args, **kwargs)
        self.fields['classroom'].disabled = True
        self.fields['classroom'].required = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM