2015-08-28 26 views
1

我有一個模型,Package設置對象權限,以便只有`owner`字段中指定的用戶才能修改對象?

class Package(models.Model): 
    VIP = models.BooleanField() 
    name = models.CharField(max_length=200) 
    contents = models.CharField(max_length=200) 
    owner = # a string, user name goes here 

對於Package任何特定實例(也就是數據庫的每一行),我想,只有其用戶名的用戶匹配owner可以修改此情況下,通過管理界面。我怎樣才能做到這一點?

+0

https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#django.contrib.auth.models.PermissionsMixin – Gocht

+0

@Gocht不知道如何解決我的問題? – becko

+0

可以修改對象_how_?在管理員?通過ORM?使用網頁表單?你需要具體。 –

回答

3

替代模型管理員的has_change_permission

class PackageAdmin(admin.ModelAdmin): 
    def has_change_permission(self, request, obj): 
     if request.user.is_super_user(): 
      # allow superusers to edit all packages 
      return True 
     if obj is None: 
      # The docs say that the method should handle obj=None 
      # Don't allow user to edit packages in general 
      return False 
     # Let the user edit the package if they are the owner. 
     return obj.owner == request.user 

上面的代碼假定所有者是一個外鍵,我推薦。如果你真的想存儲的用戶名作爲一個字符串,那麼你會改變最後一行:

return obj.owner == request.user.username 

您可以添加額外的檢查,以確保用戶對包模式「變」許可(更多信息請參見the docs)。

請注意,有一個has_delete_permission模型管理方法,您可能也想重寫。

+1

你的意思是'返回obj.owner == request.user.username',對吧? – becko

+2

是的,我的意思是'obj.owner'。通常,將所有者作爲用戶模型的外鍵會比將用戶名存儲爲字符串更好。 – Alasdair

+1

不應該'has_change_permission'包含'self'參數嗎? – becko

相關問題