Search code examples
djangotastypiedjango-testing

How to create a patch/update (i.e. update an object) request in Django test client?


I am using Django 1.5. and django-tastypie

I am testing a use case where, first I have to create an object and then update that object via rest api. e.g.

class FooTest(TestCase):
    fixtures = ['df_fixtures1.json']

    def setUp(self):
        print "SETTING UP?"
    def tearDown(self):
        print "Tear Down"
    def test_foo_delete(self):
          member1 = Client()
          member1.login(username='member1',password=test_password)
          response = member1.post('/fooapi/api/foo/?format=json', json_data, content_type="application/json") #**This creates the foo object**
          META =  {'X-HTTP-Method-Override':'PATCH'}
          response123 = member1.put(response['location'],
                        '{"isActive":0}', 
                       content_type="application/json", META = META    
                       ) **#This gives a 501**

The second request gives 501 error. On the server side there is a def obj_update i.e. a method to handle the update/patch request. What is the best way to update the object using Django client for rest api.


Solution

  • As the "PATCH" method is available from django 1.6 onwards this can be used as a hack on Django 1.5

    response123 = member1.put(response['location'],
                            data = data, 
                            content_type="application/json",
                            **{'REQUEST_METHOD':'PATCH'}
                           )
    

    This will change the method from put to PATCH. Hope this helps someone else.