kmichael08
kmichael08

Reputation: 81

Filtering objects in django admin

I want to manage objects in django admin, though I would like to be able only to edit objects with a specific value of some attribute. Precisely I have now in admin.py:

class UnitAdmin(admin.ModelAdmin):
    list_display = ('type', 'name', 'result_file')
    list_filter = ['type']
admin.site.register(Unit, UnitAdmin)

And I would like to manage only units with type='SomeSpecificType'. I saw something with overriding SimpleListFilter class, though I can't see how this applies here.

Upvotes: 1

Views: 3926

Answers (2)

itzMEonTV
itzMEonTV

Reputation: 20369

You can do

class UnitAdmin(admin.ModelAdmin):
    list_display = ('type', 'name', 'result_file')
    list_filter = ['type']

    def get_readonly_fields(self, request, obj=None):
        if obj and obj.type == 'SomeSpecificType':
            return []
        return ["type", "name", "result_file"]

Upvotes: 1

allcaps
allcaps

Reputation: 11248

You have to override the get_queryset in de modelAdmin and filter objects that have type='SomeSpecificType.

class UnitAdmin(admin.ModelAdmin):
    ...

    def get_queryset(self, request):
        qs = super(UnitAdmin, self).get_queryset(request)
        return qs.filter(type='SomeSpecificType')

Upvotes: 7

Related Questions