2

我不能让它为我的生活工作。

我在 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
4

2 回答 2

7

正确缩进(如评论中所述),但您还需要更改授权。默认情况下,Tastypie 使用ReadOnlyAuthorization不允许您发布。

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
于 2014-03-19T21:22:11.237 回答
3

谢谢你的工作

class WordResource(ModelResource):
    class Meta:
        queryset = Word.objects.all()
        resource_name = 'word'
        allowed_methods = ['get', 'post', 'put']
        authentication = Authentication()
        authorization = Authorization()

我的模型是这样的

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
于 2016-06-14T10:08:45.353 回答