Search code examples
pythondjangotastypie

Need to get the current user's id without request object in tastypie resource


In my django application, I need to get the current user's id(id of logged in user) inside tastypie resource. Here I don't have access to request object due to which I am having the problem.

Here is the file: myapi.py

from tastypie.resources import Resource

class Rating(Resource):
    def get_table(obj):
        table = Table(TABLE_NAME_2)
        return table

    class Meta:
        resource_name = 'rating'
        serializer = urlencodeSerializer()
        object_class = DynamoObject
        always_return_data = True
    def obj_get_list(self, bundle, **kwargs):
        table = self.get_table()
        ### need to get user_id from view
        user_id = 2
        items = table.query(user_id__eq = user_id, limit= 1 , consistent = True)
        items = [i for i in items]
        my_items = []
        if len(items) == 0:
            my_items.append(DynamoObject(initial={"photo_id": "0"}))
        else:
            for item in items:
                my_items.append(DynamoObject(initial=dict(item)))
        return my_items

How do I achieve this?


Solution

  • You can get access to the request object from the bundle argument. Your code then becomes

    user_id = bundle.request.user.id
    

    See the bundle docs for an explanation of this object.