Search code examples
posttastypie

Create record for authenticated user in tastypie/Django


Very simple: I have a User resource and a Item resource, as soon as a logged in user creates a new Item, I want the system to automatically create that new Item resource with user_id of the authenticated user.. simple right?

usual setup:

class Item( models.Model ):
    user = models.ForeignKey( User, related_name="item" )
    nCries = models.IntegerField(blank=True, null=True, )

class ItemResource( MyModelResource ) :

user = fields.ToOneField( 'app.api.UserResource','user',full=True,null=True)
class Meta:
    queryset = Item.objects.all()
    resource_name = 'item'
    authorization= Authorization()
    authentication = SessionAuthentication()

How do I do this with tastypie?

obj_create(self, bundle, **kwargs): wouldn't do it for me since I have no access to the request object to change the bundle.user.id to the authenticated user id.

Any idea appreciated!

THX


Solution

  • The can be also accessed via bundle.request attribute. Note that this attribute is not required, and as such might not always be available (usually when using the method outside of the regular tastypie request-response cycle).