views:

115

answers:

1

I have a such model named Foo:

class Foo(models.Model):
    name = models.CharField()
    entry = models.DateField()

I have 2 types of users who can login to the admin panel, regular and superusers. I want to disallow the edition/deletion of Foo entries that are older than 2 days (by using the entry date field) but superusers may edit without any restriction. How can I achieve this? Thanks

+4  A: 

Override ModelAdmin's queryset and has_change_permission :

from django.contrib.admin import ModelAdmin

class FooAdmin(ModelAdmin):
    def has_change_permission(self, request, obj):
        return obj is None or self.queryset(request).filter(pk=obj.pk).count() > 0

    def queryset(self, request):
        query = super(FooAdmin, self).queryset(request)
        if request.user.is_superuser:
            return query
        else:
            from datetime import datetime, timedelta 

            return query.filter(entry__gt=datetime.now()-timedelta(days=2))

admin.site.register(Foo, FooAdmin)

has_change_permission is used by the change view, and queryset by the list view. I reuse the queryset inside the overridden has_change_permission to stay DRY ( so you can add additional filters in queryset without caring to add this logic in the change permission check ), but it's worth mentioning that it costs an additional query.

vincent
thanks alot for the snipplet, you saved me :) !
Hellnar