ajax - Tastypie -- 如何让 obj_create 将新创建的实体发回?

标签 ajax django tastypie

我发送了一个 POST,它创建了一个新的简单 Resource(不是 ModelResource),并且有效。

我的问题是如何将创建的资源的 bundle 属性返回给 ajax 响应?

这是资源示例:

class MyResource(Resource):
    x = fields.CharField(attribute='x')
    y = fields.CharField(attribute='y')

    class Meta:
        resource_name = 'myresource'
        object_class = XYObject
        authorization   = Authorization()

    def obj_create(self, bundle, request=None, **kwargs):
        x = bundle.data["x"]
        x = bundle.data["y"]
        bundle.obj = XYObject(x, y)
        return bundle

这是POST请求

$.ajax({
               type: "POST",
               url: '/api/v1/myresource/',
               contentType: 'application/json',
               data: data,
               dataType: 'json',
               processData: false,
               success: function(response)
               {
                //get my resource here
               },
               error: function(response){
                   $("#messages").show('error');
                 }
               });

最佳答案

您只需将 always_return_data = True 添加到您的 Meta 中即可。然后你会得到一个带有序列化数据的 202 而不是普通的 201

来自 https://stackoverflow.com/a/10138745/931277

这是文档:http://django-tastypie.readthedocs.org/en/latest/resources.html#always-return-data

关于ajax - Tastypie -- 如何让 obj_create 将新创建的实体发回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919248/

相关文章:

jquery - : How to cache AJAX responses (to be displayed the next time the user selects a tab)?

javascript - 使用ajax提交表单时如何发送电子邮件

javascript - "[object Object]"不是有效的数字 jquery slider

Django Tastypie : post value in multiple models to a single Tastypie Resource

django - 反向关系 "ToManyField"在tastypie 和 obj_create 错误

python - 使用 tastypie 从 PointField 返回纬度和经度值

javascript - 当我无权修改其他域 API 时,如何从 Javascript 客户端向 API 发出跨域请求?

javascript - 如何在Spring中将JSP页面上的AJAX JQuery制作为 Controller ?

python - Django IntegerRangeField 验证失败

python - Django:新版本Django中的DisallowedHost