gpt4 book ai didi

django - 根据内联相关的对象,将选择限制为通用内联 FK 字段

转载 作者:行者123 更新时间:2023-12-04 21:15:57 25 4
gpt4 key购买 nike

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

例如,我有 Article,具有通用关系 Publishing,与 Article 内联编辑。

我希望 PublishingInline 以某种方式“知道”它当前正在对文章进行内联编辑,并将可用的 PublishingTypes 限制为 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

最佳答案

如果我没理解错的话formfield_for_foreignkey在你的 GenericInlineModelAdmin 上是你的 friend 。

按照这些思路应该可以做到这一点:

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)

关于django - 根据内联相关的对象,将选择限制为通用内联 FK 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6222519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com