0
我試圖設置一個模型表單集合ModelChoiceField
,以便用戶可以創建多個表單並在每個表單中從查詢集中選擇一個項目。但是,當我渲染我的formset時,它正在爲queryset中的每個對象創建一個表單。在每個表單中,ModelChoiceField
已被設置爲查詢集中的下一個對象。這是不可取的,我只想要一個表單,用戶應該選擇所需的對象,我會用JS動態創建它們。基本上,我在rulerequest表單中嵌套了應用程序表單集。Django ModelChoiceField模型formset爲每個對象創建表單
形式:
class ApplicationForm(BootstrapMixin, forms.ModelForm):
name = forms.ModelChoiceField(
queryset=Application.objects.all(),
to_field_name='name',
help_text='Application name',
error_messages={
'invalid_choice': 'Application not found.',
}
)
class Meta:
model = Application
fields = [
'name'
]
help_texts = {
'name': "Application name",
}
class RuleRequestForm(BootstrapMixin, forms.ModelForm):
class Meta:
model = RuleRequest
fields = [
'name', 'description',
]
help_texts = {
'name': 'Short name for the request',
'description': "Buisness case and summary.",
}
def __init__(self, *args, **kwargs):
super(RuleRequestForm, self).__init__(*args, **kwargs)
data = kwargs.get('data')
initial = kwargs.get('initial')
application_formset = modelformset_factory(Application, form=ApplicationForm, extra=0, min_num=1)
self.applications = application_formset(data=data, initial=initial, prefix='applications')
型號:
class Application(CreatedUpdatedModel):
name = models.CharField(
max_length=255,
null=True
)
description = models.TextField(
blank=True
)
def __str__(self):
return self.name
class RuleRequest(CreatedUpdatedModel, ST2ExecuationModel):
name = models.CharField(
max_length=255
)
description = models.TextField(
blank=False
)
applications = models.ManyToManyField(
to=Application,
related_name='rule_requests'
)
那是formset的工作。您將需要創建所需的功能。 –
@ alfonso.kim我該怎麼做?我只想初始化一個窗體,'ModelChoiceField'不應該有任何選擇。 – lampwins
請張貼您的模型代碼。 –