Django - 从ModelChoiceField中排除选项

时间:2015-03-25 15:46:27

标签: python django web frameworks

我很难尝试使用queryset从ModelChoiceField中排除选择。我对django和python不是很有经验,非常感谢你的帮助。

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

ModelForm:

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

1 个答案:

答案 0 :(得分:0)

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

我处理这个问题的方法是将实例加到表单中:

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