Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tastypie ajax POST obj_create - How to return json

Im sending a POST that creates a new User, and that works.

My question is how do I get back for example the pk of the created user to the ajax response?

         $.ajax({
                url: 'http://localhost:8080/api/v1/create/user/',
                type: 'POST',
                contentType: 'application/json',
                data: '{"uuid": "12345"}',
                dataType: 'json',
                processData: false,
                success: function (r) {
                    console.log(r)
                },
            });

def obj_create(self, bundle, request=None, **kwargs):
        try:
            user = User.objects.create_user(bundle.data['uuid'],'1')
            user.save()


        except:
            pass
        return bundle
like image 434
Harry Avatar asked Dec 27 '22 03:12

Harry


1 Answers

you can set always_return_data=True within your UserResource's Meta and on POST and PUT request it will return the created object back.

From the docs

always_return_data

Specifies all HTTP methods (except DELETE) should return a serialized form of the data. Default is False.

If False, HttpNoContent (204) is returned on POST/PUT with an empty body & a Location header of where to request the full resource.

If True, HttpAccepted (202) is returned on POST/PUT with a body containing all the data in a serialized form.

like image 70
Amyth Avatar answered Jan 09 '23 11:01

Amyth