如何在Django中从模型构建表单时过滤对象?

时间:2011-09-09 12:53:40

标签: django

class TriggerForm(ModelForm):
    class Meta:
        model = Trigger

class Trigger(models.Model):
    account = models.ForeignKey(Account)
    name = models.CharField(max_length=255)
    schedule = models.ForeignKey(Schedule)

    def __unicode__(self):
        return self.name

当显示触发器表单时,我只想显示登录帐户的计划项目,而是显示所有计划对象。

1 个答案:

答案 0 :(得分:2)

您可以将请求作为参数传递给TriggerForm,然后使用它来过滤Schedule ...

class TriggerForm(ModelForm):
    class Meta:
        model = Trigger

    def __init__(self, request=None, *args, **kwargs):
        super(TriggerForm, self).__init__(*args, **kwargs)

        self.fields['schedule'] = forms.ModelChoiceField(queryset=Schedule.objects.filter([your filter here based on the logged in user]))


#views.py

from my_app.forms import TriggerForm

def my_view(request):
    form = TriggerForm(request, request.POST or None)
    # and so on

希望能帮到你。