根据与内联相关的对象,限制对通用内联FK字段的选择

时间:2011-06-03 02:55:09

标签: django django-models django-admin

我正在尝试限制在通用内联中找到的FK字段的选择,具体取决于内联所附加的内容。

例如,我有Article,其中包含通用关系Publishing,与Article内联编辑。

我希望PublishingInline以某种方式“知道”当前正在内联编辑文章,并将可用的PublishingType限制为content_type Article

这是我做的开始:

class PublishingInlineForm(forms.ModelForm):

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

        try:
            data = kwargs.pop("data", {})
            if kwargs["instance"]:
                publishing_type_kwargs = {
                    'content_type': kwargs["instance"].content_type, }
                data["publishing_type"] = PublishingType.objects.filter(**publishing_type_kwargs)
                kwargs["data"] = data
        except KeyError:
            pass

        super(PublishingInlineForm, self).__init__(*args, **kwargs)

class PublishingInline(generic.GenericStackedInline):

    form = PublishingInlineForm

    model = get_model('publishing', 'publishing')
    extra = 0

1 个答案:

答案 0 :(得分:2)

如果我理解你GenericInlineModelAdmin def formfield_for_foreignkey(self, db_field, request, **kwargs): print self.parent_model # should give you the model the inline is attached to if db_field.name == "publishing_type": kwargs["queryset"] = ... # here you can filter the selectable publishing types based on your parent model return super(PublishingInline, self).formfield_for_foreignkey(db_field, request, **kwargs) 是你的朋友。

这些方面应该做的事情:

{{1}}