Tastypie ajax POST obj_create - 如何返回json

Har*_*rry 4 django tastypie

我发送一个创建新用户的POST,这是有效的.

我的问题是我如何回到例如创建用户的pk到ajax响应?

         $.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
Run Code Online (Sandbox Code Playgroud)

Amy*_*yth 8

您可以always_return_data=True在UserResource中进行设置Meta,在POST和PUT请求中它将返回创建的对象.

来自文档

always_return_data

指定所有HTTP方法(DELETE除外)应返回数据的序列化形式.默认值为False.

如果为False,则在POST/PUT上返回HttpNoContent(204),其中包含空主体和位置标头,其中请求完整资源.

如果为True,则在POST/PUT上返回HttpAccepted(202),其中包含序列化形式的所有数据.