The Guy
The Guy

Reputation: 718

Django Admin - Filter Choice Field based on current object being edited

I am attempting to exclude the current object being edited from a choice field to select a parent object from the same model. For example:

from django import forms
from django.contrib import admin

class RelationForm(forms.ModelForm):    
    parent = forms.ModelChoiceField(queryset=Ingredient.objects.exclude(id=current_ingredient_id))  

    def save(self, commit=True):
        parent = self.cleaned_data.get('parent', None)
        # ...do something with extra_field here...
        return super(RelationForm, self).save(commit=commit)

    class Meta:
        model = IngredientRelations
        exclude = ['description']

@admin.register(Ingredient)
class IngredientAdmin(admin.ModelAdmin):
    form = RelationForm

    fieldsets = (
        (None, {
             'fields': ('name', 'slug', 'description', 'parent',),
        }),
    ) 

The difficult comes from getting the current object being edited and then getting its primary key in the RelationForm for the queryset argument.

I have tried using ModelAdmin.formfield_for_foreignkey and ModelAdmin.formfield_for_choice_field in IngredientAdmin with no luck.

Any ideas?

Upvotes: 5

Views: 4233

Answers (1)

tutuDajuju
tutuDajuju

Reputation: 10860

The canonical method to do this is by updating the queryset in the __init__ method using currently edited instance id.

class RelationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(RelationForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['parent'].queryset = Ingredient.objects.exclude(id=self.instance.id)

    class Meta:
        model = IngredientRelations
        exclude = ['description']

originally seen in this answer: https://stackoverflow.com/a/1869917/484127

Upvotes: 2

Related Questions