我需要在 hydrate 方法中获取授权用户对象,如下所示:
class SalepointResource(ModelResource):
def hydrate(self, bundle):
user = bundle.request.user
但是这里的请求是空的HttpRequest对象,并且没有用户方法,虽然用户是授权的。有没有办法获取用户对象?
您是否在美味派中正确设置了身份验证/授权?
使用 TastyPie 0.9.15,我发现这很有效:
def hydrate_user(self, bundle):
bundle.obj.user = bundle.request.user
return bundle
无需子类化ModelResource
。这user
是ForeignKey
模型和资源的一个。我将其发布为答案,因为尽管它看起来很简单,但我花了很长时间才弄清楚。
不确定这是否是最好的方法,但我通过子类化ModelResource
该类并覆盖它的一些方法来解决这个问题。在对象ModelResource
中request
(包含user
)是方法的参数,obj_update
但它没有传递给full_hydrate
方法,而方法又调用hydrate
. 您必须对这些方法中的每一个进行一些小的更改才能将request
对象一直传递到链中。
方法修改是微不足道的。详细地:
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from tastypie.resources import ModelResource
from tastypie.exceptions import NotFound, BadRequest, InvalidFilterError, HydrationError, InvalidSortError, ImmediateHttpResponse
class MyModelResource(ModelResource):
def obj_create(self, bundle, request=None, **kwargs):
...
bundle = self.full_hydrate(bundle, request)
...
def obj_update(self, bundle, request=None, **kwargs):
...
bundle = self.full_hydrate(bundle, request)
...
def full_hydrate(self, bundle, request=None):
...
bundle = self.hydrate(bundle, request)
...
def hydrate(self, bundle, request=None):
...
return bundle
然后使您的资源成为这个新类的子类并覆盖新版本hydrate
:
class MyModelResource(MyModelResource):
class Meta:
queryset = MyModel.objects.all()
def hydrate(self, bundle, request):
bundle.obj.updated_by_id = request.user.id
return bundle
我还没有彻底测试过这个,但它似乎到目前为止工作。希望能帮助到你。