2016-03-05 167 views
1

我有Django的REST框架的一個問題,我在學習權限和關聯設置爲我的API,因此,林無法運行服務器,因此它說Asse田:現場(READ_ONLY =真)應ReadOnlyFieldDjango的REST框架:Asse田

我model.py

class Task(models.Model): 
    owner=models.ForeignKey('auth.User',related_name='tasks') 
    completed=models.BooleanField(default=False) 
    title=models.CharField(max_length=100) 
    description=models.TextField() 

serializer.py

class TaskSerializer(serializers.ModelSerializer): 
    owner=serializers.Field('owner.username') 
    class Meta: 
     model = Task 
     fields=('title','description','completed','owner ') 

permission.py

class IsOwnerOrReadOnly(BasePermission): 
    def has_object_permission(self, request, view, obj): 
     if request.method is SAFE_METHODS: 
      return True 

     return obj.owner==request.user 

views.py

class TasksMixins(object): 
    queryset = Task.objects.all() 
    serializer_class=TaskSerializer 
    permission_classes=(IsOwnerOrReadOnly,) 

    def pre_save(self,obj): 
     obj.owner=self.request.user 

class TaskList(ListCreateAPIView): 
    pass 

class TaskDetail(RetrieveUpdateDestroyAPIView): 
    pass 

林不知道我搞砸了。任何幫助非常感謝

回答

0

這個問題可能與owner.username,因爲我不知道如何直接更新。

嘗試

class TaskSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Task 
     read_only=('owner.username',) 
     fields=('title','description','completed','owner.username') 
0

的IsOwnerOrReadOnly類是試圖以比較登錄的用戶屬性的所有者,但在你的序列化,你只需要用戶名不是用戶本身,你串行器應該是這樣的:

class TaskSerializer(serializers.ModelSerializer): 
    owner_username=serializers.Field('owner.username', read_only=True) 
    class Meta: 
    model = Task 
    fields=('title','description','completed','owner', 'owner_username') 

你也需要驗證如果對象具有所有者屬性:

class IsUserOwner(BasePermission): 
    def has_object_permission(self, request, view, obj): 
     if request.method is SAFE_METHODS: 
      if not hasattr(obj, 'owner'): 
       return True 

      return obj.owner == request.user 
     return True 
+0

我得到** TypeError:__init __()得到關鍵字參數'read_only'的多個值** – Coeus