用户限制django表单ForeignKey下拉列表

时间:2012-11-28 17:12:19

标签: django django-forms

我有两个模型,Group和List Item。列表项属于组:

class List_Item(models.Model):
    name = models.CharField("List Item Name", max_length=200, unique = True)
    group = models.ForeignKey(Group, verbose_name="Group")

    creation_date = models.DateTimeField("Creation Date", default=datetime.now)
    notes = models.TextField("Notes", blank=True)

    user = models.ForeignKey(User, editable=False)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField("Group Name", max_length=200, unique = True)
    notes = models.TextField("Notes", blank=True)

    user = models.ForeignKey(User, editable=False)

    def __unicode__(self):
        return self.name

在我的列表项的表单中,ModelForm有一个Groups的下拉列表。目前,它列出了所有组,无论组属于哪个用户。但我想只显示属于登录用户的组。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您必须覆盖 init 方法中的表单字段。您可以将登录用户从视图传递到表单并根据它进行过滤

#form
class ListItemform(forms.ModelForm):
    def __init__(self. *args, **kwrgs):
            self.user = kwargs.pop('user', None)
            super(ListItemform, self).__init__(*args, **kwargs)
            self.fields['group'].queryset = Group.objects.filter(user = self.user)
#view
def displayform(request):
    user = request.user
    form = ListItemForm(user = user)
    return ...