0

我有以下型号:

class Project(models.Model):
    name = models.CharField(max_length=50)

class ProjectParticipation(models.Model):
    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)

class Receipt(models.Model):
    project_participation = models.ForeignKey(ProjectParticipation)

此外,我有以下 CreateView:

class ReceiptCreateView(LoginRequiredMixin, CreateView):
    form_class = ReceiptForm
    model = Receipt
    action = 'created'

我现在想要一个下拉菜单,用户可以在其中选择项目,新收据应该用于。用户应该只看到他被分配到的项目。我怎样才能做到这一点?

4

2 回答 2

0

我找到了使用 ModelChoiceField 的解决方案:

class ProjectModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.project

class ReceiptForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ReceiptForm, self).__init__(*args, **kwargs)
        self.fields['project_participation'] = ProjectModelChoiceField(queryset= ProjectParticipation.objects)
class Meta:
    model = Receipt

然后在 CreateView 中:

class ReceiptCreateView(...)
    def get_form(self, form_class):
        form = super(ReceiptCreateView, self).get_form(form_class)
        form.fields['project_participation'].queryset = ProjectParticipation.objects.filter(user=self.request.user)
        return form

有没有办法直接在ModelForm中过滤查询集?

于 2013-03-25T12:30:47.070 回答
0

简单的答案就是创建一个阅读文档的模型表单,这是基本的。

您可能还想查看相关名称,这样您就可以在 FK 上获得相反的信息。

class ProjectParticipation(models.Model):
    user = models.ForeignKey(User)
    project = models.ForeignKey(Project, related_name='ProjectParticipation')
于 2013-03-25T10:58:37.233 回答