Tastypie: Getting Request

These notes apply to tastypie version: 0.9.14.

I have a model that keeps track of the user that created a record. Something like:

class TestData(models.Model):
    posted_by = models.ForeignKey(User)
    post_datetime = models.DateTimeField(auto_now_add=True)
    data = models.TextField(blank=True)

 

The question is how to set the value of “posted_by” to request.user when the post is being done through the REST API? The solution is the hydrate method of ModelResouce. Like this:

class TestDataResource(ModelResource):
    class Meta:
        queryset = TestData.objects.all()
        resource_name = 'testdata'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        allowed_methods = ['get','post','put']

    def hydrate(self, bundle):
        bundle.obj.posted_by = bundle.request.user
        return bundle
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s