2

Resource新しい単純な(ModelResourceではない)を作成するPOSTを送信しましたが、それは機能します。

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');
                 }
               });
4

3 に答える 3

9

always_return_data = Trueメタに追加するだけです。202通常の ではなく、シリアル化されたデータを含む を取得します201

https://stackoverflow.com/a/10138745/931277から

ドキュメントは次のとおりです。http://django-tastypie.readthedocs.org/en/latest/resources.html#always-return-data

于 2012-10-16T17:15:29.070 に答える
2

実際、これを介してデータを保存するつもりはありません。これResourceは ajax ベースのビジネス ロジック リソースであり、いくつかのコントロールを適用する必要があります。

ImmediateHttpResponse次のように HttpResponse タイプを指定できるように、を発生させることを好みます。

def obj_create(self, bundle, request=None, **kwargs):
    bundle.data['results'] = bundle.obj.check(request)
    if bundle.data['results']['valid']:
         raise ImmediateHttpResponse(self.create_response(request, bundle,response_class = HttpCreated))
    raise ImmediateHttpResponse(self.create_response(request,  bundle.data['results']['message'],response_class = HttpBadRequest))
于 2012-10-16T22:10:38.343 に答える
0

Tastypieはpost_list(1)の方法を利用しています。そのメソッドがあなたのメソッドを呼び出しますobj_create。その後、201 CreatedHTTP 応答が返され、Location ヘッダーが設定されます。したがって、長い話を短くするために、API 呼び出しによって返されたヘッダーを確認し、ヘッダーを確認する必要があります Location

編集:

いくつかのコードが役に立ちます:

...
success: function(data, textStatus, jqXHR)
    {
    // You must look for Location
    console.log(jqXHR.getAllResponseHeaders());
    },
...

(1) https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1244

于 2012-10-16T16:52:40.603 に答える