[Django]-Django admin: how do I filter a ForeignKeyField widget based on the object's (not request.user's) data?

4👍

Just override the ModelForm being used:

class ChartAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ChartAdminForm, self).__init__(*args, **kwargs)
        if self.instance.module_id:
            self.fields['parent'].queryset = self.fields['parent'].queryset.filter(module=self.instance.module)

class ChartAdmin(admin.ModelAdmin):
    form = ChartAdminForm
    ...

2👍

From what i’ve seen in the source code, kwargs should contain only the widget (not helping !).

One possible hack, would be to override the get_form() modeladmin method, just to set request.current_object. Then, you could use request.current_object in formfield_callback:

def get_form(self, request, obj=None, **kwargs):
    request.current_object = obj
    return super(ChartAdmin, self).get_form(request, obj, **kwargs)

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    instance = request.current_object

    kwargs['queryset'] = Chart.objects.filter(module=instance.module)
    return super(ChartAdmin, self).formfield_for_foreignkey(self, db_field, request, **kwargs)
👤jpic

Leave a comment