Django - get_queryset() missing 1 required positional argument: request

2024/11/13 9:37:19

I was trying to make an API using REST Framework for uploading a file to the server and my codes are below.

If you have any other easy method to do the same please post your code.

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 extensionversion = 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=FileUploaderfields='__all__'read_only_fields = '__all__'def validate(self, validated_data):validated_data['owner'] = self.context['request'].uservalidated_data['name'] = os.path.splitext(validated_data['file'].name)[0]validated_data['size'] = validated_data['file'].sizereturn validated_datadef create(self,validated_data):return FileUploader.objects.create(**validated_data)

views.py

class FileUploaderViewSet(viewsets.ModelViewSet):serializer_class = FileUploaderSerializerparser_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()),]

My requirement is that i need to upload a file to the server and the details of the uploaded file is to be shown.

This is the error i am getting!

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'webapp'] Installed Middleware:['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"in inner41. response = get_response(request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response187. response = self.process_exception_by_middleware(e, request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"in wrapped_view58. return view_func(*args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" inview90. return self.dispatch(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch489. response = self.handle_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" inhandle_exception449. self.raise_uncaught_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch486. response = handler(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list40. queryset = self.filter_queryset(self.get_queryset())

Exception Type: TypeError at /upload/ Exception Value: get_queryset()missing 1 required positional argument: 'request'

Updated views.py file as follows

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, FormParserfrom 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):passUser=get_user_model()from .serializers import(UserCreateSerializer,UserLoginSerializer,)class UserCreateAPIView(CreateAPIView):serializer_class=UserCreateSerializerqueryset=User.objects.all()class UserLoginAPIView(APIView):permission_classes=[AllowAny]serializer_class=UserLoginSerializerdef post(self,request,*args,**kwargs):data=request.dataserializer=UserLoginSerializer(data=data)if serializer.is_valid(raise_exception=True):new_data=serializer.datareturn Response(new_data,status=HTTP_200_OK)return Response(serializer.errors,status=HTTP_400_BAD_REQUEST)class FileUploaderViewSet(viewsets.ModelViewSet):serializer_class = FileUploaderSerializerparser_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

Traceback:

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'webapp'] Installed Middleware:['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"in inner41. response = get_response(request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response187. response = self.process_exception_by_middleware(e, request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"in wrapped_view58. return view_func(*args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" inview90. return self.dispatch(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch489. response = self.handle_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" inhandle_exception449. self.raise_uncaught_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch486. response = handler(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list40. queryset = self.filter_queryset(self.get_queryset())

File "F:\proj\env\myproject\webapp\views.py" in get_queryset74. qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)

Exception Type: TypeError at /upload/ Exception Value: get_queryset()takes 1 positional argument but 2 were given


New Traceback after changeing get query set

class FileUploaderViewSet(viewsets.ModelViewSet):serializer_class = FileUploaderSerializerparser_classes=(MultiPartParser,FormParser)# overriding default query setdef get_queryset(self):qs = super(FileUploaderViewSet, self).get_queryset()qs = qs.filter(owner=self.request.user)return qs

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'webapp'] Installed Middleware:['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"in inner41. response = get_response(request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response187. response = self.process_exception_by_middleware(e, request)

File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in_get_response185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"in wrapped_view58. return view_func(*args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" inview90. return self.dispatch(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch489. response = self.handle_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" inhandle_exception449. self.raise_uncaught_exception(exc)

File "F:\proj\env\lib\site-packages\rest_framework\views.py" indispatch486. response = handler(request, *args, **kwargs)

File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list40. queryset = self.filter_queryset(self.get_queryset())

File "F:\proj\env\myproject\webapp\views.py" in get_queryset74. qs = super(FileUploaderViewSet, self).get_queryset()

File "F:\proj\env\lib\site-packages\rest_framework\generics.py" inget_queryset68. % self.class.name

Exception Type: AssertionError at /upload/ Exception Value:'FileUploaderViewSet' should either include a queryset attribute, oroverride the get_queryset() method.

Answer

get_queryset only requires self as a parameter.

Simply remove the other args.

https://en.xdnf.cn/q/72348.html

Related Q&A

Storing elements of one list, in another list - by reference - in Python?

I just thought Id jot this down now that Ive seen it - it would be nice to get a confirmation on this behavior; I did see How do I pass a variable by reference?, but Im not sure how to interpret it in…

Joining Two Different Dataframes on Timestamp

Say I have two dataframes:df1: df2: +-------------------+----+ +-------------------+-----+ | Timestamp |data| | Timestamp |stuff| +-------------------+---…

Find if the array contain a 2 next to a 2

I am stuck on this problemGiven an array of ints, return True if the array contains a 2 next to a 2 somewhere.has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → FalseI know the b…

AttributeError: xml.etree.ElementTree.Element object has no attribute encode

Im trying to make a desktop notifier, and for that Im scraping news from a site. When I run the program, I get the following error.news[child.tag] = child.encode(utf8) AttributeError: xml.etree.Element…

How to parse code (in Python)?

I need to parse some special data structures. They are in some somewhat-like-C format that looks roughly like this:Group("GroupName") {/* C-Style comment */Group("AnotherGroupName")…

Using OpenCV detectMultiScale to find my face

Im pretty sure I have the general theme correct, but Im not finding any faces. My code reads from c=cv2.VideoCapture(0), i.e. the computers videocamera. I then have the following set up to yield where …

Get marginal effects for sklearn logistic regression

I want to get the marginal effects of a logistic regression from a sklearn modelI know you can get these for a statsmodel logistic regression using .get_margeff(). Is there nothing for sklearn? I want…

How to use win32com.client.constants with MS Word?

Whats wrong with this code? Why win32com.client.constants doesnt have attribute wdWindowStateMinimize?>>> import win32com.client >>> w=win32com.client.Dispatch("Word.Applicatio…

How to properly patch boto3 calls in unit test

Im new to Python unit testing, and I want to mock calls to the boto3 3rd party library. Heres my stripped down code:real_code.py:import boto3def temp_get_variable(var_name):return boto3.client(ssm).ge…

import a github into jupyter notebook directly?

Hey Im creating a jupyter notebook, would like to install: https://github.com/voice32/stock_market_indicators/blob/master/indicators.py which is a python program not sure how to do it directly so anybo…