Django - 从 ModelChoiceField 中排除选项

Django - Exclude options from ModelChoiceField

我很难尝试使用查询集从 ModelChoiceField 中排除选项。我对 django 和 python 不是很有经验,非常感谢您的帮助。

我正在尝试创建一个表单来将用户分配给项目。 我使用内联表单集,我想从表单集中的用户组合框中删除已分配给该项目的用户。

模型形式:

class ProjectUserForm(forms.ModelForm):
    user = forms.ModelChoiceField(queryset=User.objects.all())

    def __init__(self, *args, **kwargs):
        project = kwargs.pop('project', None)
        super(ProjectUserForm, self).__init__(*args, **kwargs)

        if project:
            self.fields['user'].queryset = User.objects.exclude(project=project)

    class Meta:
    model = ProjectUser

观点:

@login_required
def project_update(request, pk):
    if pk is None:
        project = Project()
    else:
        project = Project.objects.get(id=pk)

    ProjectUserFormset = inlineformset_factory(Project, ProjectUser,
        form=ProjectUserForm(project=project),
        extra=0,
        max_num=User.objects.count(),
        fk_name='project',
        can_delete=False,
    )

    if request.method == 'POST':
        project_form = ProjectForm(
            request.POST,
            instance=project
        )
        project_user_formset = ProjectUserFormset(
            request.POST,
            instance=project,
            prefix='project_user'
        )  
        if project_form.is_valid() and project_user_formset.is_valid():
            project = project_form.save(commit=False)
            project_user_formset.save()
            project.save()

    else:
        project_form = ProjectForm(instance=project)
        project_user_formset = ProjectUserFormset(
            instance=project,
            prefix='project_user'
        )

    return render(request, "Nexquality/project_form.html", {
        'title': 'Modify project: '+project.name,
        'form': project_form,
        'project_user_formset': project_user_formset,
    })

问题是表单集工厂没有传递项目实例。它只希望您传递表单 class 本身,而不是 class 的实例。我很惊讶没有抛出错误。

我的处理方式是将实例柯里化为以下形式:

from django.utils.functional import curry

. . .
ProjectUserFormset = inlineformset_factory(Project, ProjectUser,
    form=ProjectUserForm,
    extra=0,
    max_num=User.objects.count(),
    fk_name='project',
    can_delete=False,
)
ProjectUserFormset.form = staticmethod(curry(ProjectUserForm, project=project))