Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict values that appear in Django admin select box

Tags:

python

django

In Django 1.11, I have 2 models, Foo and Bar:

class Foo(models.Model):
    name = models.CharField()
    extra = models.BooleanField(default=False)

class Bar(models.Model):
    name = models.CharField()
    extra_foo = models.ForeignKey(Foo)

My admin.py looks like this:

class BarInline(admin.StackedInline):
    model = Bar
    fields = ('name', 'extra_foo')

class FooAdmin(admin.ModelAdmin):
    fields('name')
    inlines = [BarInline]

My problem is that the in the Bar inline form, the dropdown for extra_foo shows all of my existing Foos. I want it to only show Foos for which extra is true. How can I modify the admin to restrict the available options in a select box to a subset of the whole?

like image 293
GluePear Avatar asked Oct 15 '25 03:10

GluePear


1 Answers

I guess, you can use render_change_form

class FooAdmin(admin.ModelAdmin):
     def render_change_form(self, request, context, *args, **kwargs):
         context['adminform'].form.fields['extra_foo'].queryset = Foo.objects.filter(extra=True)
         return super(FooAdmin, self).render_change_form(request, context, *args, **kwargs)

admin.site.register(Foo, FooAdmin)

If you want this to be global then have a look at limit_choices_to

extra_foo = models.ForeignKey(Foo, limit_choices_to={'extra': True})

Credit : filter foreignkey field in django admin

like image 177
Umair Mohammad Avatar answered Oct 16 '25 16:10

Umair Mohammad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!