class MyModelAdmin(admin.ModelAdmin):
...
def has_delete_permission(self, request, obj=None):
if obj is not None and \
obj.my_date_field.month == datetime.now().month and \
obj.my_date_field.year == datetime.now().year:
return False
return super(MyModelAdmin, self).has_delete_permission(request, obj=obj)
UPDATE:
這不是「永遠無」,它被設置爲一個特定的對象時的特定對象可確定。在更改列表中,尤其是在嘗試從更改列表批量刪除時的情況下,它被設置爲None
,因爲沒有明確可以確定單個對象。
如果您需要考慮從更改列表中刪除,您必須創建自己的刪除操作並替換默認的Django版本。喜歡的東西:
class MyModelAdmin(admin.ModelAdmin):
...
actions = ['limited_delete_selected']
# Need to remove the default delete_selected action
def get_actions(self, request):
actions = super(MyModelAdmin, self).get_actions(request)
if actions.has_key('delete_selected'):
del actions['delete_selected']
return actions
def limited_delete_selected(self, request, queryset):
# filter selected items to only those that are actually deletable
now = datetime.now()
queryset = queryset.exclude(date_field__month=now.month, date_field__year=now.year)
# call Django's delete_selected with limited queryset
from django.contrib.admin.actions import delete_selected
delete_selected(self, request, queryset)
limited_delete_selected.short_description = "Delete selected objects or whatever you want it to say"
實際上,您將需要兩個動作和原始has_delete_permission
因爲對象可以單獨對他們change_form視圖中刪除。
優秀答案Chris – Brandon
如果我在管理員中選擇幾個模型實例並刪除它們,has_delete_permission中的obj變量始終爲None。我編輯了我的問題。 – jul