我尝试使用REST Framework创建一个API,用于将文件上传到服务器,我的代码在下面。
如果您有任何其他简单的方法,请发布您的代码。
models.py
from django.db import models
# Create your models here.
class FileUploader(models.Model):
file = models.FileField()
name = models.CharField(max_length=100) #name is filename without extension
version = models.IntegerField(default=0)
upload_date = models.DateTimeField(auto_now=True, db_index=True)
owner = models.ForeignKey('auth.User', related_name='uploaded_files')
size = models.IntegerField(default=0)
def __str__(self):
return self.name
serializers.py
class FileUploaderSerializer(serializers.ModelSerializer):
class Meta:
model=FileUploader
fields='__all__'
read_only_fields = '__all__'
def validate(self, validated_data):
validated_data['owner'] = self.context['request'].user
validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
validated_data['size'] = validated_data['file'].size
return validated_data
def create(self,validated_data):
return FileUploader.objects.create(**validated_data)
views.py
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
def get_queryset(self,request, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(self,request, *args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
urls.py
from django.conf.urls import url
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
from webapp.views import(
UserCreateAPIView,
UserLoginAPIView,
FileUploaderViewSet,
)
router = routers.DefaultRouter()
router.register(r'upload', views.FileUploaderViewSet,base_name='file-view')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
#url(r'^upload/$',FileUploaderViewSet.as_view()),
]
我的要求是我需要将文件上传到服务器,并显示上传文件的详细信息。
这是我得到的错误!
环境:
请求方法:GET请求网址:http://127.0.0.1:8000/upload/
Django版本:1.11.7 Python版本:3.6.3已安装的应用程序: [' django.contrib.admin',' django.contrib.auth', ' django.contrib.contenttypes',' django.contrib.sessions', ' django.contrib.messages',' django.contrib.staticfiles', ' rest_framework',' webapp']已安装的中间件: [' django.middleware.security.SecurityMiddleware&#39 ;, ' django.contrib.sessions.middleware.SessionMiddleware&#39 ;, ' django.middleware.common.CommonMiddleware&#39 ;, ' django.middleware.csrf.CsrfViewMiddleware&#39 ;, ' django.contrib.auth.middleware.AuthenticationMiddleware&#39 ;, ' django.contrib.messages.middleware.MessageMiddleware&#39 ;, ' django.middleware.clickjacking.XFrameOptionsMiddleware']
回溯:
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ exception.py" 在内心 41. response = get_response(request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 187. response = self.process_exception_by_middleware(e,request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 185. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ django \ views \ decorators \ csrf.py" 在wrapped_view中 58. return view_func(* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ viewsets.py"在 视图 90.返回self.dispatch(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 489. response = self.handle_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 handle_exception 449. self.raise_uncaught_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 486. response = handler(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ mixins.py"在列表中 40. queryset = self.filter_queryset(self.get_queryset())
异常类型:TypeError at / upload / Exception值:get_queryset() 缺少1个必要的位置参数:'请求'
更新了 views.py 文件,如下所示
from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import viewsets
from rest_framework.status import HTTP_200_OK,HTTP_400_BAD_REQUEST
from .models import employees
from .serializers import (
employeesSerializer,
FileUploaderSerializer,
)
from django.contrib.auth import get_user_model
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
ListAPIView,
RetrieveAPIView,
RetrieveUpdateAPIView,
)
from rest_framework.permissions import(
AllowAny,
IsAuthenticated,
IsAdminUser,
IsAuthenticatedOrReadOnly,
)
class employeeList(APIView):
def get(self,request):
employees1=employees.objects.all()
serializer=employeesSerializer(employees1,many=True)
return Response(serializer.data)
def post(self):
pass
User=get_user_model()
from .serializers import(
UserCreateSerializer,
UserLoginSerializer,
)
class UserCreateAPIView(CreateAPIView):
serializer_class=UserCreateSerializer
queryset=User.objects.all()
class UserLoginAPIView(APIView):
permission_classes=[AllowAny]
serializer_class=UserLoginSerializer
def post(self,request,*args,**kwargs):
data=request.data
serializer=UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data=serializer.data
return Response(new_data,status=HTTP_200_OK)
return Response(serializer.errors,status=HTTP_400_BAD_REQUEST)
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
# overriding default query set
#queryset = LayerFile.objects.all()
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
回溯:
环境:
请求方法:GET请求网址:http://127.0.0.1:8000/upload/
Django版本:1.11.7 Python版本:3.6.3已安装的应用程序: [' django.contrib.admin',' django.contrib.auth', ' django.contrib.contenttypes',' django.contrib.sessions', ' django.contrib.messages',' django.contrib.staticfiles', ' rest_framework',' webapp']已安装的中间件: [' django.middleware.security.SecurityMiddleware&#39 ;, ' django.contrib.sessions.middleware.SessionMiddleware&#39 ;, ' django.middleware.common.CommonMiddleware&#39 ;, ' django.middleware.csrf.CsrfViewMiddleware&#39 ;, ' django.contrib.auth.middleware.AuthenticationMiddleware&#39 ;, ' django.contrib.messages.middleware.MessageMiddleware&#39 ;, ' django.middleware.clickjacking.XFrameOptionsMiddleware']
回溯:
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ exception.py" 在内心 41. response = get_response(request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 187. response = self.process_exception_by_middleware(e,request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 185. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ django \ views \ decorators \ csrf.py" 在wrapped_view中 58. return view_func(* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ viewsets.py"在 视图 90.返回self.dispatch(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 489. response = self.handle_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 handle_exception 449. self.raise_uncaught_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 486. response = handler(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ mixins.py"在列表中 40. queryset = self.filter_queryset(self.get_queryset())
文件" F:\ proj \ env \ myproject \ webapp \ views.py"在get_queryset中 74. qs = super(FileUploaderViewSet,self).get_queryset(self,* args,** kwargs)
异常类型:TypeError at / upload / Exception值:get_queryset() 需要1个位置参数但是给出了2个
更改获取查询集后的新跟踪
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
# overriding default query set
def get_queryset(self):
qs = super(FileUploaderViewSet, self).get_queryset()
qs = qs.filter(owner=self.request.user)
return qs
环境:
请求方法:GET请求网址:http://127.0.0.1:8000/upload/
Django版本:1.11.7 Python版本:3.6.3已安装的应用程序: [' django.contrib.admin',' django.contrib.auth', ' django.contrib.contenttypes',' django.contrib.sessions', ' django.contrib.messages',' django.contrib.staticfiles', ' rest_framework',' webapp']已安装的中间件: [' django.middleware.security.SecurityMiddleware&#39 ;, ' django.contrib.sessions.middleware.SessionMiddleware&#39 ;, ' django.middleware.common.CommonMiddleware&#39 ;, ' django.middleware.csrf.CsrfViewMiddleware&#39 ;, ' django.contrib.auth.middleware.AuthenticationMiddleware&#39 ;, ' django.contrib.messages.middleware.MessageMiddleware&#39 ;, ' django.middleware.clickjacking.XFrameOptionsMiddleware']
回溯:
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ exception.py" 在内心 41. response = get_response(request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 187. response = self.process_exception_by_middleware(e,request)
文件" F:\ proj \ env \ lib \ site-packages \ django \ core \ handlers \ base.py"在 _get_response 185. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ django \ views \ decorators \ csrf.py" 在wrapped_view中 58. return view_func(* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ viewsets.py"在 视图 90.返回self.dispatch(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 489. response = self.handle_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 handle_exception 449. self.raise_uncaught_exception(exc)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ views.py"在 调度 486. response = handler(request,* args,** kwargs)
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ mixins.py"在列表中 40. queryset = self.filter_queryset(self.get_queryset())
文件" F:\ proj \ env \ myproject \ webapp \ views.py"在get_queryset中 74. qs = super(FileUploaderViewSet,self).get_queryset()
文件" F:\ proj \ env \ lib \ site-packages \ rest_framework \ generics.py"在 get_queryset 68.%self。 class 。名称
异常类型:/ upload / Exception值的AssertionError: ' FileUploaderViewSet'应该包含
queryset
属性,或者 覆盖get_queryset()
方法。
答案 0 :(得分:1)
get_queryset()不期望'请求'。也许删除“请求”'来自get_queryset()的参数。供参考,您可以查看: get_queryset()
也许是这样的:
def get_queryset(self, *args, **kwargs):
qs = your_model.objects.all()
qs = qs.filter(owner=self.request.user)
return qs
答案 1 :(得分:1)
Sayse说,只需要self
。但您不必将self
传递给get_queryset()
。 self
只是一个实例,super
本身就是自我实例。
所以只需从
更改以下行super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
到
super(FileUploaderViewSet, self).get_queryset()
<强>更新强>
您确定,您的get_queryset
是否在同一个班级?
您是否尝试过编写queryset = Model.objects.all()
?
我在您的视图中看不到model = ModelName
。
view class
应该有以下字段。
def get_queryset(self):
return queryset
serializer_class = SerializerClass
model = ModelName
答案 2 :(得分:0)
get_queryset
仅需要self
作为参数。
只需删除其他参数。
答案 3 :(得分:0)
get_queryset
不期望请求参数,并且DRF基类不会传递它。但它可用作实例属性。您应该从方法签名和超级调用中删除它,并通过self.request
访问它。
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs