我尝试了这种方法来使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 动态?
谢谢。
答案 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)