Search code examples
djangodjango-modelsdjango-modeladmin

Limiting the options of foreign key in ModelAdmin returns "Select a valid choice"


I am attempting to limit the option to a foreign key in the admin app for a specific user (The field that i am trying to limit is called school) . This is what my code looks like - Unfortunately there are two problems (mentioned below) when I attempt to edit a student (by clicking on their name).

1.The default value for school is --

2.When I select the right school from the drop down and attempt to save I get the error on school field saying

Select a valid choice. That choice is not one of the available choices.

This is what it looks like

enter image description here

class modelStudentAdmin(admin.ModelAdmin):   

     def get_queryset(self, request):
        qs = super(modelStudentAdmin, self).get_queryset(request)

        if request.user.is_superuser:
            return qs
        else:
            schoolInstance = modelSchool.objects.get(user=request.user)
            qs = modelStudent.objects.filter(school=schoolInstance)
            return qs

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.user.is_superuser:
            return super(modelStudentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

        #Not superuser only staff
        if db_field.name == 'school':
            t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True)
            kwargs['queryset'] = t

        return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)

Now if I remove the method

def formfield_for_foreignkey(self, db_field, request, **kwargs):

everything works but then I cannot restrict the foreign key. Any suggestions on what I might be doing wrong ?


Solution

  • Try replacing

     t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True)
    

    with this

    modelSchool.objects.filter(user=request.user)
    

    you dont need to value_list your query set.