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 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()),
]
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 inner 41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in view 90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list 40. 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, 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
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 inner 41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in view 90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list 40. queryset = self.filter_queryset(self.get_queryset())
File "F:\proj\env\myproject\webapp\views.py" in get_queryset 74. 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 = 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
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 inner 41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in view 90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list 40. queryset = self.filter_queryset(self.get_queryset())
File "F:\proj\env\myproject\webapp\views.py" in get_queryset 74. qs = super(FileUploaderViewSet, self).get_queryset()
File "F:\proj\env\lib\site-packages\rest_framework\generics.py" in get_queryset 68. % self.class.name
Exception Type: AssertionError at /upload/ Exception Value: 'FileUploaderViewSet' should either include a
queryset
attribute, or override theget_queryset()
method.