filtering dropdown values in django admin

后端 未结 4 1552
野的像风
野的像风 2020-12-09 17:27
class Foo(models.Model):
    title = models.TextField()
    userid = models.IntegerField()
    image = models.CharField(max_length=100)
    def __unicode__(self):
           


        
相关标签:
4条回答
  • 2020-12-09 17:39

    You could subclass your own model.ModelAdmin and create a custom field for your ChoiceField...

    class CustomForm(model.ModelForm):
    
        class Meta:
            model = Foo
    
        foo = forms.ChoiceField(widget=forms.Select, initial=self.foo_queryset)
    
        def foo_queryset(self):
            return Foo.objects.filter(xy)...
    
    class FooAdmin(model.ModelAdmin):
        form = CustomForm
    
    0 讨论(0)
  • 2020-12-09 17:44

    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

    0 讨论(0)
  • 2020-12-09 17:48

    I stumbled across this question when looking for a solution to filter dropdown options on the fly in the admin interface based on the selection in another field -- not based on a pre-filtered list at page load. The solution I found was this library: https://github.com/digi604/django-smart-selects which is an app that uses ajax calls and allows chain filtering to multiple levels. Works like a charm for me. -HTH

    0 讨论(0)
  • 2020-12-09 17:50

    for django 1.6:

    For foreign key: https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#ModelAdmin.formfield_for_foreignkey

    class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "title":
            kwargs["queryset"] = Foo.objects.filter(title__isnull=False)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
    
    0 讨论(0)
提交回复
热议问题