过滤django admin下拉列表中的字段

时间:2014-02-01 10:45:02

标签: python html django django-admin django-admin-filters

我有一个非常简单的django模型:

class Car(models.Model):
   carname = models.CharField(max_length=100)
   carmodel = models.CharField(max_length=100)
   carcountry = models.CharField(max_length=100)
   caryear = models.CharField(max_length=100)
       cardesc = models.TextField()

以及显示所有记录的admin.py:

class UserForm(forms.ModelForm):
    cardesc = forms.CharField(widget=forms.Textarea(attrs={'cols': 120, 'rows': 20}))

class Meta:
    model = Cars


  class ModelAdmin(admin.ModelAdmin ):
     form = UserForm



  admin.site.register(Cars,ModelAdmin)

它工作正常。现在,我的问题是: 我想要一个下拉列表,我可以选择汽车模型,然后根据我的选择过滤我的结果...

我怎么能这样做?我要编辑Admin.py文件? Django有内置功能吗?或者我必须创建一个HTML模板?怎么样?请帮帮我。

3 个答案:

答案 0 :(得分:5)

试试这个。

class CustomForm(forms.ModelForm):

    class Meta:
        model = Cars

    cars_list = Cars.objects.values_list('carmodel', flat=True).order_by('carmodel').distinct()
    choice_list = []
    for car in cars_list:
        choice_list.append((car,car,)) 
    CAR_CHOICES = choice_list

    #Used 'ChoiceField' as you want dropdown list for carmodels stored in text fields 
    carmodel = forms.ChoiceField(widget=forms.Select, choices=CAR_CHOICES)

class CarsModelAdmin(model.ModelAdmin):
    form = CustomForm
    list_filter = ['carmodel']

admin.site.register(Cars,CarsModelAdmin)

答案 1 :(得分:2)

您必须添加

list_filter = ['carmodel', ]

到ModelAdmin类。

答案 2 :(得分:2)

来自documentation

ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)¶
     

ModelAdmin上的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)
     

这使用HttpRequest实例过滤Car外键字段,仅显示User实例拥有的汽车。