Reputation: 3145
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?
Upvotes: 2
Views: 2101
Reputation: 421
I don't know whether is it feasible or not in your case but you can read inside the request before the control goes to the API using a middleware in django. After reading the request object in middleware, you may forward it you API object. More on django middleware
Upvotes: -1
Reputation: 1605
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.
Upvotes: 4