ModelForms和ForeignKeys

时间:2013-03-25 10:09:55

标签: django django-forms

我有以下型号:

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'

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

2 个答案:

答案 0 :(得分:0)

简单的答案就是创建一个model form阅读文档,这是基础。

您可能还想查看related names,这样您可以在FK上反过来。

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

答案 1 :(得分: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中过滤查询集的解决方案?