Search code examples
pythondjangotastypie

tastypie overid create_response() method


I tring to override tastypie create_response because I have some verification to do before sending response to user. this is my code:

class MyNamespacedModelResource(NamespacedModelResource):
    def create_response(self , request , data):
        r = super(MyNamespacedModelResource , self).create_response(request , data , response_class=HttpResponse)
            # ... some treatements...
        return r

And I have user NamespaceModelResource who work fine before.

When I tring to add new user ( with post method) , I have got this

error:

create_response() got an unexpected keyword argument 'response_class'

Solution

  • You have defined the method create response() with two positional arguments. However, the super class definition looks like this:

    def create_response(self, request, data, response_class=HttpResponse, **response_kwargs)
    

    Why this is a problem is that your overridden method is called with keyword arguments that you haven't "accepted" in your definition. That's what the **response_kwargs stands there for. It means this function can have an infinite number of keyword args. Your definition can have 0. So if you change your definition to either create_response(self, request, data, **kwargs) or create_response(self, request, data, response_class=HttpResponse, **response_kwargs), you'll be rid of this problem. But you'll have another one on your hands. In 99% of the cases, keyword arguments must be passed on to the super class method. So the ideal version in most cases is to just duplicate both the definition and super() method call, which in your case looks like this:

    class MyNamespacedModelResource(NamespacedModelResource):
        def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
            r = super(MyNamespacedModelResource , self).create_response(request, data, response_class=response_class, **response_kwargs)
    
            return r