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



所以我使用ModelFormSet来显示基于预定义ModelForm的表单列表。我需要自定义表单中的两个字段,因此我创建了这个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',
]

我正在以下视图中创建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)

基本上,我遇到的问题是,当我在forms.py中的StudentRelationshipForm中指定classroom字段时,HTMLSelect小部件的默认值变成---------。但是,如果我从forms.py中删除该行,则HTML选择小部件在编辑现有实例时会正确地从数据库中选择教室名称。

我该如何克服这一点?我需要该行的原因是指定应该禁用该字段。如果还有其他方法可以实现这一点,请告诉我

第页。S.:我需要表单中的disabled=True,而不是模板中的,因为disabled=True防止用户发送与初始输入不同的输入,即使他们更改了HTML源。

我通过在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

相关内容

  • 没有找到相关文章

最新更新