Daryl
Daryl

Reputation: 1489

Limiting choices to an Generic Inline FK field dependant on the object that the Inline is being related to

I'm trying to limit the choices of a FK field found in a generic inline, depending on what the inline is attached to.

For example I have Article, with a Generic relation Publishing, edited inline with the Article.

I'd like for the PublishingInline to 'know', somehow, that it is currently being edited inline to an Article, and limit the available PublishingTypes to content_type Article.

This is the start that I've made:

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

Upvotes: 3

Views: 491

Answers (1)

arie
arie

Reputation: 18982

If i understand you correctly formfield_for_foreignkey on your GenericInlineModelAdmin is your friend.

Something along these lines should do it:

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)

Upvotes: 2

Related Questions