[Fixed]-How can I limit the choices in an InlineAdmin based on the current instance?

1👍

Here’s the answer I figured out myself. Feel free to edit, comment, or provide a better solution!

I created a custom form for editing SiteArticles, which I passed to the ArticleAdmin using the form option of ModelAdmin. In the constructor of this form I performed the filtering of the queryset based on the current model instance, which is now available as self.instance.

class CustomSiteArticleForm(forms.ModelForm):
    class Meta:
        model = SiteArticle
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(CustomSiteArticleForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['tags'].queryset = self.instance.site.tags.all()
        else:
            self.fields['tags'].queryset = Tag.objects.none()

Leave a comment