Django ModelForm with ModelChoiceField and Query Filter



我需要从传递到单个公司表单中的数据在下拉列表中创建一个案例列表。

我将 id 传递到表单中,但我如何在 CaseChoiceField 查询中使用它?

仅在查询中使用 id 或 self.id 不起作用。

首先在视图中:

form = NewProjectCaseForm ( id = f.id )

模型形式:

class NewProjectCaseForm ( forms.Form ):
    # get all the cases for the firm
    # how do I get the ID from below ???
    case = CaseChoiceField ( queryset = Case.objects.filter (firm_id = id ) )
    def __init__ ( self, *args, **kwargs ):
        # id from the view
        self.id = kwargs.pop ( 'id' )
        super ( NewProjectCaseForm, self ).__init__ ( *args, **kwargs )
        self.helper = FormHelper ()
        self.helper.layout = Layout (
        Div (
            Div ( 'case', css_class = 'large-10 cell' ),
            css_class = 'grid-x'
        ),
        ButtonHolder (
            Submit ( 'submit', 'Add Case', css_class = 'button small-6' )
        )
    )

要创建下拉列表,我使用这个:

class CaseChoiceField ( ModelChoiceField ):
    def label_from_instance ( self, obj ):
        return '{} - {}'.format ( obj.name, obj.firm )

我正在使用脆皮形式(用于粉底(

我希望这是有道理的。

谢谢。

您必须使用如下所示__init__方法。

self.fields['case'] = CaseChoiceField (queryset=Case.objects.filter(firm_id=self.id))

现在,表单如下所示

class NewProjectCaseForm ( forms.Form ):
    def __init__ ( self, *args, **kwargs ):
        # id from the view
        self.id = kwargs.pop ( 'id' )
        super ( NewProjectCaseForm, self ).__init__ ( *args, **kwargs )
        self.fields['case'] = CaseChoiceField (queryset=Case.objects.filter(firm_id=self.id))
        self.helper = FormHelper ()
        self.helper.layout = Layout (
        Div (
            Div ( 'case', css_class = 'large-10 cell' ),
            css_class = 'grid-x'
        ),
        ButtonHolder (
            Submit ( 'submit', 'Add Case', css_class = 'button small-6' )
        )
    )

最新更新