我有一个模型和资源。我使用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);
}
});