Search code examples
pythondjangocurltastypie

PUT method not working in django-tastypie?


I am new to django-tastypie. Here my api.py code,

from tastypie.resources import ModelResource
from .models import ListModel


class ListModelResource(ModelResource):

    def determine_format(self, request):
        return 'application/json'

    class Meta:
        allowed_methods = ['get','put']
        queryset = ListModel.objects.all()

Here I am using CURL for GET:

curl http://127.0.0.1:8000/api/v1/listmodel/1/

OUT: {"completed": false, "id": 1, "resource_uri": "/api/v1/listmodel/1/", "title": "This is test"}

Here I am using CURL for PUT:

 curl --dump-header - -H "Content-Type: application/json" '{"completed": false, "id": 1, "resource_uri": "/api/v1/listmodel/1/", "title": "This is test"}' http://127.0.0.1:8000/api/v1/listmodel/1/
HTTP/1.0 401 UNAUTHORIZED
Date: Wed, 04 Sep 2013 08:12:53 GMT
Server: WSGIServer/0.1 Python/2.7.2+
Content-Type: text/html; charset=utf-8

Why I am getting 401 ?.


Solution

  • According to tastypie tutorial:

    ... if you try sending a POST/PUT/DELETE to the resource, you find yourself getting “401 Unauthorized” errors. For safety, Tastypie ships with the authorization class (“what are you allowed to do”) set to ReadOnlyAuthorization. This makes it safe to expose on the web, but prevents us from doing POST/PUT/DELETE. ..

    You can enable it using tastypie.authorization.Authorization:

    from tastypie.authorization import Authorization
    from tastypie.resources import ModelResource
    from .models import ListModel
    
    class ListModelResource(ModelResource):
        def determine_format(self, request):
            return 'application/json'
    
        class Meta:
            allowed_methods = ['get','put']
            queryset = ListModel.objects.all()
            authorization= Authorization() # <---
    

    Warning

    This is now great for testing in development but VERY INSECURE. You should never put a Resource like this out on the internet. Please spend some time looking at the authentication/authorization classes available in Tastypie.