Django tastypie'POST'在模型上使用覆盖save()

时间:2014-07-20 05:59:56

标签: python django tastypie

我在我的模型上使用tastypieoauth2覆盖save(),尝试使用POST {/ 1} curl --dump-header - -H "Authorization: OAuth MYTOKEN" -H "Content-Type: application/json" ":21.21, "longitude":12.32}' http://localhost:8000/api/v1/location/新对象>

我的目标是使用资源创建新对象,但也使用User凭据保存对象。

现在我收到此错误:{"error_message": "save() takes exactly 2 arguments (1 given)"...}

我的位置模型中的覆盖保存():

def save(self, request):
    if self.latitude and self.longitude:
        self.gps_location = Point(self.latitude, self.longitude)
    if not self.id:
        self.created = datetime.datetime.now()
    self.updated = datetime.datetime.now()
    if hasattr(request,'user'):
        self.created_by = request.user
    else:
        self.created_by = None
    super(Location, self).save()

我的资源:

class LocationResource(ModelResource):
    class Meta:
        fields = ['created', 'updated', 'latitude', 'longitude',]
        queryset = Location.objects.all()
        resource_name = 'location'
        allowed_methods = ['post', 'get', 'put']
        filtering = {'type':ALL_WITH_RELATIONS}
        authorization = DjangoAuthorization()
        authentication = OAuth20Authentication()
        include_resource_uri = False

    def create_obj(self, bundle, **kwargs):
        try:
            old_save = bundle.obj.save
            bundle.obj.save = partial(old_save, user=bundle.request.user)
            return super(LocationResource, self).save(bundle)
        finally:
            bundle.obj.save = old_save
        bundle.obj.created_by = bundle.request.user
        #return super(LocationResource, self).obj_create(bundle, user=bundle.request.user)

    def hydrate(self, bundle):
        bundle.obj.user = bundle.request.user
        return bundle

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

我发现了this帖子,并尝试了两个解决方案的建议(如上所示),但没有帮助。

如何将请求对象发送到模型上的overover save()或以其他方式解决?

1 个答案:

答案 0 :(得分:0)

hydrate()上的重叠created_by为我解决了这个问题。我的解决方案:

request移除模型(created_bysave()分配):

def save(self):
    if self.latitude and self.longitude:
        self.gps_location = Point(self.latitude, self.longitude)
    if not self.id:
        self.created = datetime.datetime.now()
    self.updated = datetime.datetime.now()
    super(Location, self).save()

资源(参见变更评论):

class LocationResource(ModelResource):
    class Meta:
        # stays the same

    def create_obj(self, bundle, **kwargs):
        # with this solution- no need to override create_obj

    def hydrate(self, bundle):
        bundle.obj.created_by = bundle.request.user # changed from bundle.obj.user to bundle.obj.created by - my mistake
        return bundle

    def apply_authorization_limits(self, request, object_list):
        # stays the same

现在,当我提到问题curl时,我得到CREATED响应,当然会创建一个新节点。

由于