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

Tastypie: the missing manual

I am using tastypie to try and get a REST interface working on a Django site. The API needs to be password protected. The problem is the docs assume you already know how authorize thru REST.

It’s actually trivial once you realize that the phrase “basic authentication” is actually a single entity; “basic-authentication” . Doing basic-authentication is pretty easy using the the python package “requests“. Just jump to the section in their docs. As easy as falling off a log.