我正在尝试将查询集传递给表单的字段。我试图显示由当前项目过滤的开发人员(我通过slug获得当前项目)。不幸的是,我收到了一个错误global name 'project' is not defined
。似乎参数没有从表单实例传递到forms.py文件或其他东西......
这是我的forms.py:
class TaskForm(ModelForm):
class Meta:
model = Task
fields = ('iteration', 'story', 'description', )
def __init__(self, *args, **kwargs):
self.project = kwargs.pop('project')
super(TaskForm, self).__init__(*args, **kwargs)
self.fields['developer'] = forms.ModelMultipleChoiceField(queryset = Developer.objects.filter(project = project)) # this is where I want my objects to filter
这就是我初始化表单的方式:
project = Project.objects.get(user=user, slug=slug)
taskForm = TaskForm(request.POST, project = project)
这是模型:
class Developer(models.Model):
task = models.ManyToManyField(Task)
我认为解决方案非常明显,但我无法让它发挥作用。
答案 0 :(得分:3)
您正在尝试调用未定义的变量项目。
请改用 self.project 。
def __init__(self, *args, **kwargs):
self.project = kwargs.pop('project')
super(TaskForm, self).__init__(*args, **kwargs)
self.fields['developer'] = forms.ModelMultipleChoiceField(queryset = Developer.objects.filter(project = self.project))