简体   繁体   English

如何在外键而不是主外键的表单上过滤模型字段

[英]How do I filter a model field on a form that is a foreignkey but not the main foreignkey

I have an inlineformset_factory that is a group of ShoppingListItemForm 我有一个inlineformset_factory,它是一组ShoppingListItemForm

View: 视图:

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)

...This works great, except 'category' is a foreign key of ShoppingListItem, and I need to filter the 'category' options offered on my form to only those which are related to ListItemCategory by 'shoppinglist'. ...这很好用,除了'category'是ShoppingListItem的外键,而且我需要将表单上提供的'category'选项过滤为仅由'shoppinglist'与ListItemCategory相关的选项。 'shoppinglist' is a foreign key of both ListItemCategory and ShoppingListItem. “购物清单”是ListItemCategory和ShoppingListItem的外键。

Models: 楷模:

class ListItemCategory(models.Model):
    name = models.CharField(max_length=30, blank=True, null=True)
    shoppinglist = models.ForeignKey(ShoppingList)

class ShoppingListItem(models.Model):
    shoppinglist = models.ForeignKey(ShoppingList)
    category = models.ForeignKey(ListItemCategory, blank=True, null=True, default = None)
    item = models.CharField(max_length=200, blank=True, null=True)

class ShoppingList(models.Model):
    name = models.CharField(max_length=30, blank=True, null=True, default="Pod List")

...I think there is no need to pass in the 'shoppinglist' as an extra argument, as it is passed as the instance of the form, but with this initialization added, my rendered template has nothing at all in the formset. ...我认为不需要将“购物清单”作为额外的参数传递,因为它是作为表单的实例传递的,但是添加了初始化之后,我呈现的模板在表单集中根本没有任何内容。

Any further advice? 还有其他建议吗?

Your issue is that you're not "initializing" the variable shoppinglist_id in your form def init 您的问题是您没有在表单def init “初始化”变量shoppinglist_id

Try this: 尝试这个:

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)

And you should edit also how to initialize the form: 并且您还应该编辑如何初始化表单:

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

The changes made are the next ones: 接下来进行的更改是:

  1. Pass the shoppinglist_id as a kwarg argument shoppinglist_id传递为kwarg参数

...ShoppingListItemForm(shoppinglist_id=shoppinglist.id)

  1. Get the kwarg argument in your form 在表格中获取kwarg参数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM