2012-01-26 71 views
1

中刪除我希望只允許某些實例的刪除操作(我的模型有一個DateTimeField,我想禁用刪除此字段設置爲當前月份的實例的操作)。只允許某個模型的某些給定實例從管理模型中的管理員

有人可以幫忙嗎?

感謝

編輯

我試着在下面一行雁克里斯提出的方法,但obj是始終無:

class UserProfileAdmin(admin.ModelAdmin): 

    def has_delete_permission(self, request, obj=None): 

     # obj is always None 

     return super(UserProfileAdmin, self).has_delete_permission(request, obj=obj) 

回答

4
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視圖中刪除。

+0

優秀答案Chris – Brandon

+0

如果我在管理員中選擇幾個模型實例並刪除它們,has_delete_permission中的obj變量始終爲None。我編輯了我的問題。 – jul

相關問題