简体   繁体   English

使用自定义 ModelForm 时,ModelFormSet 中的 ModelChoiceField 未选择初始值

[英]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 .所以我使用ModelFormSet来显示基于预定义 ModelForm 的ModelForm列表。 I need to customize the two fields in the forms, and therefore I have created this ModelForm :我需要自定义 forms 中的两个字段,因此我创建了这个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:我正在以下视图中创建ModelFormSet

# 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 --------- .基本上我遇到的问题是,当我在StudentRelationshipFormforms.py中指定classroom字段时, HTML Select 小部件的默认值变为--------- 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.但是,如果我从 forms.py 中删除该行,HTML select 小部件会在编辑现有实例时正确地从数据库中选择教室名称。

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. PS:我需要表单中的disabled=True而不是模板,因为disabled=True会阻止用户发送与初始输入不同的输入,即使他们更改了 HTML 源。

I managed to resolve the issue by specifying the attributes of the field in the __init__ of the Form :我设法通过在Form__init__中指定字段的属性来解决问题:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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