简体   繁体   中英

Django MultipleChoiceField and model instance

I am trying to pass a queryset to form's field. I am trying to display developers that are filtered by current project (I am getting current project by slug). Unfortunately, I am getting an error, that global name 'project' is not defined . It seems that the argument doesn't pass from form instance to the forms.py file or something...

This is my 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

This is how I am initialising the form:

project = Project.objects.get(user=user, slug=slug)
taskForm = TaskForm(request.POST, project = project)

This is the model:

class Developer(models.Model):
task = models.ManyToManyField(Task)

I think that the solution is pretty obvious, but I can't get it working.

You are trying to call variable project which is not defined.
Use self.project instead.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM