问题
I need to get authorized user object in hydrate method, something like that:
class SalepointResource(ModelResource):
def hydrate(self, bundle):
user = bundle.request.user
But request here is empty HttpRequest object, and doesn't have user method, although user is authorized. Is there any way to get user object?
回答1:
With TastyPie 0.9.15, I find this works:
def hydrate_user(self, bundle):
bundle.obj.user = bundle.request.user
return bundle
with no need for subclassing ModelResource
. Here user
is a ForeignKey
of the model and the resource.
I'm posting this as an answer because although it looks simple, it took me a long time to figure out.
回答2:
Have you set up authentication/authorization properly in tastypie?
回答3:
Not sure if this is the best approach, but I got around this problem by subclassing the ModelResource
class and overriding some of its methods. In ModelResource
the request
object (which contains user
) is a parameter to the obj_update
method but it is not passed on to the full_hydrate
method, which in turn calls hydrate
. You have to make a few small changes to each of these methods to pass the request
object all the way down the chain.
The method modifications are trivial. In detail:
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
Then make your resource a subclass of this new class and override the new version of 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
I haven't tested this thoroughly but it seems to work so far. Hope it helps.
来源:https://stackoverflow.com/questions/9785454/how-to-get-authorized-user-object-in-django-tastypie