user1687717
user1687717

Reputation: 3475

how to make a JSON response after create a resource successfully?

I'm building a Django-Tastypie server. After I create a resource successfully, the server will response me "201 created", but the Content-Type is text/html. I want the resource always return JSON response, how to do it?

Here's my resource code

class UserResource(ModelResource):

    class Meta:
        resource_name = "user"
        queryset = User.objects.all()
        authentication = Authentication()
        authorization = Authorization()

        allowed_methods=["post"]
        fields= ["username","email","id"]


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

Upvotes: 0

Views: 104

Answers (1)

Calvin Cheng
Calvin Cheng

Reputation: 36556

Try adding

always_return_data = True 

to your Meta.

And when you execute your POST, make sure that the url you are posting to has ?format=json at the end. E.g.

http://127.0.0.1:8000/api/v1/user/?format=json

Full example of a POST via curl:-

curl -v -H "Content-Type: application/json" -X POST --data '{"username":"calvin", "email":"[email protected]", "id": "1"}' http://127.0.0.1:8000/api/v1/user/?format=json

Upvotes: 1

Related Questions