我不能让这个为我的生活而工作。
我在api.py
中有这个class catResource(ModelResource):
class Meta:
queryset = categories.objects.all()
resource_name = 'categories'
allowed_methods = ['get', 'post', 'put']
authentication = Authentication()
所以当我尝试时:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name":"Test", "parent": "0", "sort": "1","username":"admin","password":"password"}' http://192.168.1.109:8000/api/v1/categories/
我明白了:
HTTP/1.0 401 UNAUTHORIZED
Date: Sat, 21 Sep 2013 10:26:00 GMT
Server: WSGIServer/0.1 Python/2.6.5
Content-Type: text/html; charset=utf-8
模特:
class categories(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', blank=True,null=True)
sort = models.IntegerField(default=0)
def __unicode__(self):
if self.parent:
prefix = str(self.parent)
else:
return self.name
return ' > '.join((prefix,self.name))
@classmethod
def re_sort(cls):
cats = sorted([ (x.__unicode__(),x) for x in cls.objects.all() ])
for i in range(len(cats)):
full_name,cat = cats[i]
cat.sort = i
super(categories,cat).save()
def save(self, *args, **kwargs):
super(categories, self).save(*args, **kwargs)
self.re_sort()
class Admin:
pass
答案 0 :(得分:6)
正确缩进您的缩进(如评论中所述),但您还需要更改授权。默认情况下,Tastypie使用ReadOnlyAuthorization
,不允许您进行POST。
https://django-tastypie.readthedocs.org/en/latest/authorization.html
class catResource(ModelResource):
class Meta:
queryset = categories.objects.all()
resource_name = 'categories'
allowed_methods = ['get', 'post', 'put']
authentication = Authentication()
authorization = Authorization() # THIS IS IMPORTANT
答案 1 :(得分:2)
谢谢你的工作
class WordResource(ModelResource):
class Meta:
queryset = Word.objects.all()
resource_name = 'word'
allowed_methods = ['get', 'post', 'put']
authentication = Authentication()
authorization = Authorization()
mY模型就像这样
class Word(models.Model):
word = models.CharField(max_length=50,unique=True)
meaning = models.TextField(max_length=150)
phrase = models.TextField(max_length=150)
sentence = models.TextField(max_length=150)
image_url = models.TextField(max_length=2000)
def __str__(self):
return self.word
别忘了
from tastypie.authorization import Authorization
from tastypie.authentication import Authentication