我正在尝试使用PATCH请求发布多个对象,但是我收到此错误:
"error_message": "'HttpRequest' object has no attribute 'user'"
我的资源模型如下:
class TrackerResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Tracker.objects.all()
resource_name = 'tracker'
allowed_methods = ['post','patch','put']
detail_allowed_methods = ['post','patch','put']
authentication = ApiKeyAuthentication()
authorization = Authorization()
always_return_data = True
fields = ['data','tracker_date','badges','module','completed']
def hydrate(self, bundle, request=None):
bundle.obj.user = bundle.request.user
bundle.obj.ip = bundle.request.META.get('REMOTE_ADDR','0.0.0.0')
bundle.obj.agent = bundle.request.META.get('HTTP_USER_AGENT','unknown')
return bundle
我正在制作的卷曲请求是(使用正确的api_key):
curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X PATCH --data '{"objects":[{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":1},{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":0}]}' "http://localhost/python/modules/api/v1/tracker/?username=alex&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx"
如果我只使用以下命令发布单个对象,它的工作正常。
curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data '{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":0}' "http://localhost/python/modules/api/v1/tracker/?username=alex&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx"
因此,当我发出PATCH请求时,能够访问当前用户对象的正确方法是什么?或者我是否需要做一些事情来使PATCH请求向每个水合物方法发送当前请求?
任何帮助都非常感激。
答案 0 :(得分:0)
好吧,我现在已经开始工作了,需要在我的TrackerResource中添加一个patch_list方法:
def patch_list(self,request,**kwargs):
request = convert_post_to_patch(request)
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
for data in deserialized["objects"]:
data = self.alter_deserialized_detail_data(request, data)
bundle = self.build_bundle(data=dict_strip_unicode_keys(data))
bundle.request.user = request.user
self.obj_create(bundle, request=request)
return http.HttpAccepted()
不确定这是否真的是处理它的最佳方式,但对我有用。