首页 > 解决方案 > 如何修复 django rest 框架元类冲突

问题描述

我是一个初学者学习 django rest 框架,我只是遇到了这个错误,我似乎找不到解决方法。这是 permissions.py 示例代码

from rest_framework import permissions

class UpdateOwnProfile(permissions, BaseException): 
"""Allow user to edit their own profile"""

 def has_object_permission(self, request, view, obj):
    """Check if user is trying to update their own profile"""
    if request.method in permissions.SAFE_METHODS:
        return True

    return obj.id == request.user.id

这也是views.py示例代码的示例

from rest_framework.views import APIView 
from rest_framework.response import Response 
from rest_framework import status 
from rest_framework import viewsets 
from rest_framework.authentication import TokenAuthentication

from profiles_api import serializers 
from profiles_api import models from profiles_api import permissions

class HelloApiView(APIView): """Test Api view""" serializer_class = serializers.HelloSerializer

def get(self, request, format=None):
    """Returns a list of Api features"""
    an_apiview = [
        'Uses HTTP methods as function (get, post, patch, put, delete)',
        'Is similar to a traditional Django view',
        'Gives you the most control over your application logic',
        'Is mapped manually to URLs',
    ]
    return Response({'message': 'Hello', 'an_apiview': an_apiview})

def post(self, request):
    """Create a hello message with our name"""
    serializer = self.serializer_class(data=request.data)

    if serializer.is_valid():
        name = serializer.validated_data.get('name')
        message = f'Hello {name}'
        return Response({'message': message})
    else:
        return Response(
            serializer.errors,
            status = status.HTTP_400_BAD_REQUEST
        )

def put(self, request, pk=None):
    """Handling updates of objects"""
    return Response({'method': 'PUT'})

def patch(self, request, pk=None):
    """Handle a partial update of an object"""
    return Response({'method': 'PATCH'})

def delete(self, request, pk=None):
    """Delete an object"""
    return Response({'method': 'DELETE'})
class HelloViewset(viewsets.ViewSet): """Test API Viewset""" serializer_class = serializers.HelloSerializer

def list(self, request):
    """Return a hello message"""
    a_viewset = [
        'Uses actions (list, create, retrieve, update, partial update'
        'Automatically maps to URLs using router'
        'provides more functionality with less code'
    ]
    return Response({'message': 'Hello', 'a_viewset': a_viewset})

def create(self, request):
    """Create a new hello message"""
    serializer = self.serializer_class(data=request.data)

    if serializer.is_valid():
        name = serializer.validated_data.get('name')
        message = f'Hello {name}!'
        return Response({'message': message})
    else:
        return Response(
            serializer.errors,
            status=status.HTTP_400_BAD_REQUEST
        )
def retrieve(self, request, pk=None):
    """Handle getting an object by its ID"""
    return Response({'http_method': 'GET'})

def update(self, request, pk=None):
    """Handle updating an object"""
    return Response({'http_method': 'PUT'})

def partial_update(self, request, pk=None):
    """Handle updating of an object"""
    return Response({'http_method': 'PATCH'})

def destroy(self, request, pk=None):
    """Handle removing an object"""
    return Response({'http_method': 'DELETE'})
class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,)

在运行开发服务器时出现此错误:

class UpdateOwnProfile(permissions, BaseException):TypeError:元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类

标签: djangodjango-rest-framework

解决方案


permissions( rest_framework.permissions) 是类型module(其类型是typeFWIW),但类型BaseExceptiontype(与所有常规类一样)。所以你有一个预期的元类冲突。

据推测,您打算使用permissions.BasePermission模块中的类:

class UpdateOwnProfile(permissions.BasePermission, BaseException):
    ...
    ...

您也可以直接导入和引用该类:

from rest_framework.permissions import BasePermission

class UpdateOwnProfile(BasePermission, BaseException):
        ...
        ...

推荐阅读