0

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

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

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

4

1 回答 1

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 ...
于 2012-11-28T17:21:54.850 回答