2013-10-23 23 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