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