更新: 私は非常に後方の方法でデータの PUT/更新を行うことができます - 私にはバグまたはセキュリティ ホールのように思えますか?
ProjectViewModel.prototype.edit = function (projectId, project) {
var _project = JSON.parse(project);
_project.id = projectId;
_project.name = "test 123!";
project = JSON.stringify(_project);
$.ajax({
url: "http://" + window.location.href.split("/")[2] + "/api/v1/project/",
type: "POST",
data: project,
contentType: "application/json",
processData: false,
success: function (data) {
$("#div_response").text("updated!");
},
error: function (data) {
$("#div_response").text(data.responseText);
}
});
};
上記のコードにより、新しいオブジェクトを Tastypie に POST できます。オブジェクト ID 値を含めると、新しいオブジェクトを作成するのではなく、既存のオブジェクトを更新します。
元の質問:
Tastypie で GET と POST はできますが、PUT または PATCH はできません。これが私のAPIを見てください:
from tastypie.resources import ModelResource
from tastypie.authentication import Authentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie import fields
from ProjectTrackerServer.projects.models import Project
from ProjectTrackerServer.milestones.models import Milestone
class ProjectResource(ModelResource):
# namespace-to-milestones, related_name-from-milestones-model, show-full
milestones = fields.ToManyField('ProjectTrackerServer.projects.api.MilestoneResource', 'projects', full=True)
class Meta:
queryset = Project.objects.all()
resource_name = 'project'
allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
authentication = Authentication()
authorization = Authorization()
class MilestoneResource(ModelResource):
project = fields.ToOneField('ProjectTrackerServer.projects.api.ProjectResource', 'project')
class Meta:
queryset = Milestone.objects.all()
resource_name = 'milestone'
allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
authentication = Authentication()
authorization = Authorization()
そして、'projectId' がメソッドの引数である私の Javascript Ajax コードの簡単なレビュー:
//this is just a test for using PUT/PATCH by fetching a project,
//updating it, and saving it back to the server.
$.ajax({
url: "http://" + window.location.href.split("/")[2] + "/api/v1/project/" + projectId + "/",
type: "GET",
data: "",
contentType: "application/json",
processData: false,
success: function (data) {
var project = data;
project.name = "Project Y!";
project.slug = "project-y";
var jsondata = JSON.stringify(project);
$.ajax({
url: "http://" + window.location.href.split("/")[2] + "/api/v1/project/" + projectId + "/",
type: "PATCH",
data: jsondata,
contentType: "application/json",
processData: false,
crossDomain: true,
headers: {
"X-HTTP-Method-Override": "PATCH"
},
success: function (data) {
$("#div_response").text(data.responseText);
},
error: function(data) {
$("#div_response").text(data.responseText);
}
});
},
error: function (data) {
$("#div_response").text(data.responseText);
}
});
興味深いのは、エラーが表示されないことです。JSON.stringify() を使用して「データ」を出力しようとすると、結果として二重引用符 ("") が表示されます。
それが役立つ場合は、私のモデルも含めています。
from django.db import models
from django.template.defaultfilters import slugify
class Project(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateField()
end_date = models.DateField()
pm_id = models.IntegerField()
status = models.IntegerField()
slug = models.SlugField()
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)[:50]
return super(Project, self).save(*args, **kwargs)
更新: GET と POST は問題なく実行できるので、curl がホストを解決できないと応答している理由がわかりません。これは、cURL を使用して取得した結果です。
C:\curl>curl --dump-header - -H "Content-Type: application/json" -X PUT --data
{{"end_date": "2014-10-10", "id": "16", "milestones": [], "name": "Project XY!
"resource_uri": "/api/v1/project/16/", "slug": "project-x", "start_date": "20
-12-30", "status": 1}}' http://localhost:1231/api/v1/project/16
curl: (6) Could not resolve host: (nil); No data record of requested type
curl: (6) Could not resolve host: (nil); Host not found
curl: (6) Could not resolve host: (nil); No data record of requested type
curl: (6) Could not resolve host: (nil); Host not found
curl: (3) [globbing] illegal character in range specification at pos 2
curl: (6) Could not resolve host: (nil); Host not found
curl: (6) Could not resolve host: (nil); No data record of requested type
curl: (6) Could not resolve host: (nil); Host not found
curl: (3) <url> malformed
curl: (6) Could not resolve host: (nil); Host not found
curl: (6) Could not resolve host: (nil); No data record of requested type
curl: (6) Could not resolve host: (nil); Host not found
curl: (6) Could not resolve host: (nil); No data record of requested type
curl: (6) Could not resolve host: (nil); Host not found
curl: (3) [globbing] unmatched close brace/bracket at pos 2
HTTP/1.0 301 MOVED PERMANENTLY
Date: Wed, 20 Feb 2013 19:58:56 GMT
Server: WSGIServer/0.1 Python/2.7.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf-8
Location: http://localhost:1231/api/v1/project/16/
Access-Control-Allow-Headers: Origin,Content-Type,Accept