Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

python - 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 foo Which is a drop down list and shows all the titles. Some title of Foo 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

from django import forms
from django.contrib import admin

#Create custom form with specific queryset:
class CustomBarModelForm(forms.ModelForm):
    class Meta:
        model = Bar
        fields = '__all__'

    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...

docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...