Question

i have a very simple django model:

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()

and a admin.py that shows the all records:

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)

it works fine. now, my question is that: i want to have a drop down list and i can select car model and then my results filtered based my choice...

how i can do that? i have to edit Admin.py file? Django has a builtin feature for this? or i have to create an HTML template? how? please help me.

Was it helpful?

Solution 2

You would have to add

list_filter = ['carmodel', ]

to class ModelAdmin.

OTHER TIPS

Try this .

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)

From the documentation:

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

The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field. For example, to return a subset of objects for this foreign key field based on the user:

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)

This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top