2013-09-23 156 views
2

我無法得到這個爲我的生活工作。django tastypie 401未授權

我有這樣的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

那麼,[文檔](http://django-tastypie.readthedocs.org/en/latest/tutorial.html)說你需要對POST請求進行某種認證......(看看「401」) –

+0

'allowed_methods'和'authentication'應該在'Meta'裏面。 –

+0

Arent他們在元? – R0b0tn1k

回答

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

謝謝你,工作

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