我有一个模型和资源。我使用 ajax 来更新资源。我可以做 PUT,但是当我做 PATCH 时,它给了我 401。我想知道问题可能出在哪里。
模型:
from django.db import models
from django.contrib.auth.models import User
from freebie.models import Freebie
# Create your models here.
class Claim(models.Model):
claimer = models.ForeignKey(User, related_name='claimer')
claim_item = models.ForeignKey(Freebie, related_name='claim_item')
PENDING = 'pending'
APPROVED = 'approved'
STATUS_CHOICES = (
(PENDING, 'pending'),
(APPROVED, 'approved'),
)
status = models.CharField(
max_length=40,
choices=STATUS_CHOICES,
default=PENDING
)
资源:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import SessionAuthentication
from tastypie.authorization import Authorization
from tastypie.constants import ALL_WITH_RELATIONS
from claim.models import Claim
from accounts.resources import UserResource
from freebie.resources import FriendsFreebieResource
from django.contrib.auth.models import User
class ClaimResource(ModelResource):
claimer = fields.ToOneField(UserResource, 'claimer', full=True)
claim_item = fields.ToOneField(FriendsFreebieResource, 'claim_item')
class Meta:
queryset = Claim.objects.all()
resource_name = 'claim'
authorization = Authorization()
authentication = SessionAuthentication()
list_allowed_methods = ['get', 'post', 'put', 'patch']
detail_allowed_methods = ['get', 'post', 'put', 'patch']
always_return_data = True
filtering = {'claimer': ALL_WITH_RELATIONS,
'claim_item': ALL_WITH_RELATIONS}
def hydrate(self, bundle):
# No pk means this is claimer posting the first claim.
if not bundle.obj.pk:
bundle.obj.claimer = \
User.objects.get(pk=bundle.request.user.id)
else:
bundle.data['claimer'] = bundle.obj.claimer
return bundle
Ajax,PATCH 不起作用,给出 401,PUT 工作正常:
var data = {};
data.status = "approved";
$.ajax({
url:'/api/v1/claim/'+claim_id+"/",
type:'PATCH', // Change to PUT, everything works.
contentType:'application/json',
dataType: "json",
data: JSON.stringify(data),
success: function(data) {
$claimer_list.empty();
var $approved_li = $('<li>')
.text("Given to " + claim.claimer.first_name + " " + claim.claimer.last_name);
$claimer_list.append($approved_li);
},
error: function(error) {
alert(error);
console.log(error);
}
});