PUT request to django tastypie resource not working

可紊 提交于 2019-12-04 10:23:02

This is because you are trying to issue a put request, but put request goes for update record and not a creating new one. Tastypie will try to execute obj_update method and it expects to be executed on some instance. But you are making request to register_user/ url which is obviously is not an object instance, so it doesnt make a sense at all to use put request for this url. PUT is for updating, not creating.

I just solve it with some modifications. Using hydrate method i can catch the request method (like put ou post) and process my requests. Like this:

class UserResource(ModelResource):
   class Meta:
       queryset = User.objects.all()
       resource_name = 'auth/user'
       fields = ['username', 'email','password','extra_data','provider']
       authentication = BasicAuthentication()
       authorization = DjangoAuthorization()
       filtering = {
            "username": ('exact',),
       }

   def prepend_urls(self):
       return [
           url(r"^(?P<resource_name>%s)/(?P<username>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
       ]

   def hydrate(self, bundle):
       request_method=bundle.request.META['REQUEST_METHOD']

       if request_method=='POST':
          #do something if you want
       elif request_method=='PUT':
          #do something if you want
       return bundle

And to test i've created a python file with this:

def basic_authorization(user, password):
    s = user + ":" + password
    return "Basic " + s.encode("base64").rstrip()

url = 'http://192.168.1.114:8080/api/stats/auth/user/david/'
payload = {'username':'david', 'email':'david__@gmail.com', 'password':'xxxx','provider':'twitter','extra_data': {'access_token':'xxxx','id':'xxx'}}
headers = {'content-type': 'application/json'}
r = requests.put(url, data=json.dumps(payload), headers=headers, auth=HTTPBasicAuth('xxx', 'xxx')) 

print r.status_code
print r.history
print r.content

post()

And it worked!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!