我收到错误:“AttributeError:类型对象‘UserList’没有属性‘as_view’”,就像,它没有看到“as_view()”
Userapp 中的 My urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('list', UserList.as_view(), name = 'user-view')
]
views.py:| ||序列化器.py:
from django.shortcuts import render
from rest_framework.views import APIView
from django.contrib.auth.models import User
from .serializer import UserSerializer
from rest_framework import response
class UserList():
def get(self, request, *args, **kwargs):
user_list = User.objects.all()
serializer = UserSerializer(instance = user_list, many = True)
return response(data = serializer.data)
serializers.py:
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['username', 'email', 'first_name',]
此错误是由于你的
UserList
类未从必要的 Django Rest Framework (DRF) 类继承而引起的。要解决此问题,你需要让你的
UserList
类继承自
APIView
或
ListAPIView
。
以下是修改后的代码:
views.py
from django.shortcuts import render
from rest_framework.views import APIView, ListAPIView # 导入 ListAPIView
from django.contrib.auth.models import User
from .serializer import UserSerializer
from rest_framework import response
from rest_framework.permissions import IsAdminUser
# 继承自 ListAPIView 用于更简洁的代码
class UserList(ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAdminUser] # 仅允许管理员访问此视图
# 你可以使用 APIView 来实现更自定义的逻辑,但需要自己处理分页等
# class UserList(APIView):
# def get(self, request, *args, **kwargs):
# user_list = User.objects.all()
# serializer = UserSerializer(instance=user_list, many=True)
# return response(data=serializer.data)
解释:
-
导入
ListAPIView
: 我们从rest_framework.views
导入ListAPIView
。 -
继承自
ListAPIView
或APIView
:-
ListAPIView
已经内置了处理列表视图的逻辑,你只需要设置queryset
和serializer_class
属性即可。 -
如果你需要更灵活的自定义逻辑,可以使用
APIView
,但需要自己处理数据获取、序列化和响应。
-
-
设置权限:
添加
permission_classes = [IsAdminUser]
来限制只有管理员用户可以访问用户列表。
通过这些修改,
UserList
类将继承
as_view()
方法,你将不再遇到
AttributeError
。