【问题标题】:How do I filter a model field on a form that is a foreignkey but not the main foreignkey如何过滤作为外键但不是主外键的表单上的模型字段
【发布时间】:2015-07-26 20:40:12
【问题描述】:

我有一个 inlineformset_factory,它是一组 ShoppingListItemForm

查看:

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)

...这很好用,除了“类别”是 ShoppingListItem 的外键,我需要将表单上提供的“类别”选项过滤为仅通过“购物清单”与 ListItemCategory 相关的选项。 'shoppinglist' 是 ListItemCategory 和 ShoppingListItem 的外键。

型号:

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")

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

还有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    您的问题是您没有在表单 def init 中“初始化”变量 shoppinglist_id

    试试这个:

    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 参数传递

    ...ShoppingListItemForm(shoppinglist_id=shoppinglist.id)

    1. 在表单中获取 kwarg 参数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2021-01-27
      • 2016-04-24
      相关资源
      最近更新 更多