Tauquir Tauquir - 1 year ago 115
Python Question

filtering dropdown values in django admin

class Foo(models.Model):
title = models.TextField()
userid = models.IntegerField()
image = models.CharField(max_length=100)
def __unicode__(self):
return self.title

class Bar(models.Model):
foo = models.ForeignKey(Foo, related_name='Foo_picks', unique=True)
added_on = models.DateTimeField(auto_now_add=True)

In Django admin add_view:

def add_view(self, *args, **kwargs):
self.exclude = ("added_on",)
self.readonly_fields = ()
return super(Bar, self).add_view(*args, **kwargs)

So, Field shows in the admin add view is
Which is a drop down list and shows all the titles. Some
remains empty or ''. So, drop down list have lots of empty value because it title is empty. I want to filter out those empty values.

Answer Source

You can provide your own form for ModelAdmin, with custom queryset for foo field.

#Create custom form with specific queryset:
class CustomBarModelForm(forms.ModelForm):
    class Meta:
        model = Bar
    def __init__(self, *args, **kwargs):
        super(CustomBarModelForm, self).__init__(*args, **kwargs)
        self.fields['foo'].queryset = Foo.objects.filter(title__isnull=False)# or something else

# Use it in your modelAdmin
class BarAdmin(admin.ModelAdmin):
    form = CustomBarModelForm

Something like this...


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download