Search code examples
pythondjangotastypie

Django Tastypie create API which accepts POST data but not creates any entry in database


My question is exactly what it's subject says :
How to create Django Tastypie API which accepts the POST data, does some processing on it and returns some HTTP response, but does not creates any entry in database.


For Example for this sample API resource :

class NextNumberResource(ModelResource):
class Meta:
    resource_name = 'next_number'
    detail_allowed_methods = []
    list_allowed_methods = ['post']


def obj_create(self, bundle, **kwargs):

    #raise CustomBadRequest(code = "code ={c}".format(c=int(bundle.data["number"])*2))
    next_number = int(bundle.data["number"]) * 2
    data = json.dumps({"next_number":next_number})
    return HttpResponse(data, content_type='application/json', status=200)

I am getting following error :
{"error_message": "'HttpResponse' object has no attribute 'pk'"}


Solution

  • I think it's better to handle this request in dispatch_* methods (e.g. dispatch_list).

    For example here.

    Explanation: If you handle a post request which doesn't create any instance, you have to process it before std workflow of the tastypie.