2013-10-23 29 views
5

使用TastyPie我有一個模型資源,它有一個FK用戶。當我發表的帖子中的API我必須包括用戶ID是這樣的:用戶爲FK的模型資源TastyPie API

data : JSON.stringify({ name : 'value a', user : '12' }), 

我的用戶可以通過登錄或使用API​​密鑰和用戶名和密碼進行身份驗證要麼。在這兩種情況下我已經知道誰是用戶

1)如何讓用戶確定user1不會爲user2創建資源?

2)或者根本不符合發送用戶ID的要求?我應該以某種方式從授權細節中獲取用戶,如果是這樣的話?

回答

3

要回答問題#1:Tastypie文檔介紹how to create per-user resources。假設用戶已經是請求的一部分:

class MyResource(ModelResource): 
    class Meta: 
     queryset = MyModel.objects.all() 
     resource_name = 'environment' 
     list_allowed_methods = ['get', 'post'] 
     authentication = ApiKeyAuthentication() 
     authorization = Authorization() 

    # Only allow creation of objects belonging to the user 
    def obj_create(self, bundle, **kwargs): 
     return super(EnvironmentResource, self).obj_create(bundle, user=bundle.request.user) 

    # Only allow accessing resources for this user 
    def apply_authorization_limits(self, request, object_list): 
     return object_list.filter(user=request.user) 

要回答問題#2,您應該讓用戶成爲會話的一部分。

+0

obj_create()中super()的第一個arg是不是'MyResource'? – DavidF