开发者

How can I filter objects when building a form from a model in Django?

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

class Trigger(models.M开发者_如何学运维odel):
    account = models.ForeignKey(Account)
    name = models.CharField(max_length=255)
    schedule = models.ForeignKey(Schedule)

    def __unicode__(self):
        return self.name

When the trigger form is shown I only want to show schedule items that are for the logged in account but instead it shows me all schedule objects.


You can pass in the request as an argument to the TriggerForm and then use that to filter the 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

Hope that helps you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜