1

更新:我能够以非常倒退的方式对数据进行 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 发布一个新对象,如果我包含对象 id 值,我将更新现有对象而不是创建一个新对象。

原始问题:

我可以 GET 和 POST,但无法使用 Tastypie 进行 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()

快速回顾一下我的 Javascript Ajax 代码,其中 'projectId' 是该方法的参数:

//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)

更新:我能够很好地获取和发布,所以我不确定为什么 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
4

0 回答 0