mt_
mt_

Reputation: 129

formfield_for_foreignkey seems to do nothing

I am following the scheme shown here and in various other places: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

My code looks like this:

class StudentAdmin(admin.ModelAdmin):

    #...

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        groups = [group.name for group in request.user.groups.all()]
        if 'principal' in groups:
            school = request.user.principal.school
            if db_field == "room":
                kwargs['queryset'] = Room.objects.filter(school=school)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    list_display = ('surname','givennames', 'room')
    list_filter = ('room',)

I have verified that the code is invoked and school is set correctly, but no filtering on the selector is happening. That is, I can see all the room instances regardless of their respective value for school.

Once deployed in the real world, the list will show far too many items, most that the user will not want to and should not see. But the filtering is not happening. Any ideas what I've missed?

Is it relevant that school itself is a foreign key to room? That has worked fine in other filters

Also I would like similar filtering on the list_filter on the select view, but this code isn't even invoked there. Advice much appreciated.

Upvotes: 1

Views: 3124

Answers (2)

mt_
mt_

Reputation: 129

following the scheme shown here and in various other places: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

My repaired code looks like this:

class StudentAdmin(admin.ModelAdmin):

#...

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    groups = [group.name for group in request.user.groups.all()]
    if 'principal' in groups:
        school = request.user.principal.school
        if db_field.name == "room": # This was the error; 
                                    # nothing wrong with the example; 
                                    # I just bobbled the retranscription
            kwargs['queryset'] = Room.objects.filter(school=school)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

list_display = ('surname','givennames', 'room')
list_filter = ('room',)

Upvotes: 0

Ehsan Nouri
Ehsan Nouri

Reputation: 2040

change the db_field checking to this:

 if db_field.name == "room":

Upvotes: 2

Related Questions