1 回答
TA贡献1872条经验 获得超3个赞
您需要将默认的 Sample queryset 设置为 none:
class CRSForm(forms.ModelForm):
class Meta:
model = ClinicallyReportedSample
fields = ('sample_id', 'evidence',)
sample_id = forms.ModelChoiceField(queryset=Sample.objects.none())
def __init__(self, *args, **kwargs):
super(CRSForm, self).__init__(*args, **kwargs)
然后当你创建一个表单集实例时,像这样手动分配查询集:
def get(self, request, *args, **kwargs):
sample_obj = Sample.objects.filter(id__in=[1, 2, 3])
formset = modelformset_factory(
ClinicallyReportedSample,
form=self.crsform,
formset=BaseCRSFormSet,
extra=3,
)
formset = formset(queryset=sample_obj)
for form in formset:
form.fields['sample_id'].queryset = sample_obj
请注意,您还必须在 POST 函数中手动设置查询集,否则将无法验证。
添加回答
举报