Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Admin Choices Using limit_choices_to

Tags:

python

django

I would like to limit the choices for a ForeignKey in the admin UI using limit_choices_to; however, I would like to achieve this without changing the model, since the model is brought in from a library, that I don't have control over. What is the way of dynamically achieving this? Or could I use a field on the admin model to be able to achieve this?

Thanks, --Eytan

like image 541
daniyalzade Avatar asked Nov 22 '11 04:11

daniyalzade


1 Answers

Django provides an admin hook to modify a foreign keys queryset: formfield_for_foreignkey

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
like image 135
Yuji 'Tomita' Tomita Avatar answered Nov 17 '22 17:11

Yuji 'Tomita' Tomita