将ModelForm选项限制为特定模型的选项

时间:2019-11-05 07:49:58

标签: django django-models

我尝试了这种方法来使project_id动态化,但出现错误:“ init ()缺少1个必需的位置参数:'project_id'”。

forms.py

class CreateCostForm(forms.ModelForm):

    def __init__(self,project_id,*args, **kwargs):

        super(CreateCostForm, self).__init__(*args, **kwargs)
        self.fields['cost_name'].queryset = ProjectCost.objects.filter(project_name_id=project_id)

    class meta:
        model = ProjectCost

当我将project_id的值硬编码为:

self.fields['project_name'].queryset = ProjectCost.objects.filter(project_name_id=4) or 
ProjectCost.objects.filter(project_name_id= 8),

我在表单上获得了正确的过滤选项。那么如何使 project_id 动态?

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试从project_id获取kwargs,例如:

def __init__(self, *args, **kwargs):
    project_id = kwargs.pop('project_id', None)
    super(CreateCostForm, self).__init__(*args, **kwargs)
    self.fields['cost_name'].queryset = ProjectCost.objects.filter(project_name_id=project_id)