如何筛选作为外键但不是主外键的表单上的模型字段

时间:2015-05-15 02:49:50

标签: django foreign-key-relationship inline-formset

我有一个inlineformset_factory,它是一组ShoppingListItemForm

查看:

ImageLoader

...这很有用,除了'category'是ShoppingListItem的外键,我需要将我的表单上提供的'category'选项过滤到只有'shoppinglist'与ListItemCategory相关的选项。 'shoppinglist'是ListItemCategory和ShoppingListItem的外键。

型号:

class ShoppingListItemForm(ModelForm):
    @property
    def __name__(self):
        return self.__class__.__name__

    def __init__(self, *args, **kwargs):

        if kwargs.get('instance'):

            theList = kwargs['instance']
            self.fields['category'] = forms.ChoiceField(choices=[(cat.id, cat.name) for cat in ListItemCategory.objects.filter(shoppinglist__id=theList.id)])

        return super(ShoppingListItemForm, self).__init__(self, *args, **kwargs)



    class Meta:
        model = ShoppingListItem
        fields = ('item', 'brand', 'quantity', 'current', 'category', 'size', )


@login_required
def shoppinglist(request, shoppinglist_id, pod_id):
    profile = request.user.get_profile()
    shoppinglist = get_object_or_404(ShoppingList, pk=shoppinglist_id)

    ListFormSet = inlineformset_factory(ShoppingList, ShoppingListItem, form=ShoppingListItemForm, extra=1, can_delete=True)

    myForms = ListFormSet(instance=shoppinglist)

...我认为没有必要将'shoppinglist'作为额外的参数传递,因为它作为表单的实例传递,但是添加了这个初始化,我的渲染模板在表单集。

还有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您的问题是您没有"初始化"表单shoppinglist_id

中的变量def init

试试这个:

class ShoppingListItemForm(ModelForm):
    class Meta:
        model = ShoppingListItem
        fields = ('item', 'brand', 'quantity', 'current', 'category', 'size', )

    def __init__(self, *args, **kwargs):
        shoppinglist_id = kwargs.pop('shoppinglist_id', None)
        super(ShoppingListItemForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = ListItemCategory.objects.filter(shoppinglist__id=shoppinglist_id)

您还应该编辑如何初始化表单:

ListFormSet = inlineformset_factory(ShoppingList, ShoppingListItem, form=ShoppingListItemForm(shoppinglist_id=shoppinglist.id), extra=1, can_delete=True)

所做的更改是下一步:

  1. shoppinglist_id作为 kwarg 参数
  2. 传递

    ...ShoppingListItemForm(shoppinglist_id=shoppinglist.id)

    1. 在表单中获取 kwarg 参数

      def __init__(self, *args, **kwargs): shoppinglist_id = kwargs.pop('shoppinglist_id', None)