VerificationSMSCode() got an unexpected keyword argument 'phone' - python

Hello everyone! I'm working on a big project with Django Rest and I'm totally stuck with this one.
The project is something like Social network and I don't know why but everything seems to be correct, but every time I do "POST" method in the browser while debugging I see this error. I can provide you more information if you need it.
urls.py
from rest_framework import routers
from auth2.api.views import SendCodeView, VerifyCodeView
router = routers.DefaultRouter()
urlpatterns = []
router.register(r'code_send', SendCodeView, basename='code_send')
urlpatterns += router.urls
views.py
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.authentication import get_authorization_header
from rest_framework import generics, status, views
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from auth2.api.serializers import SendCodeSerializer, VerifyCodeSerializer
from auth2.models import VerificationSMSCode
from core.api.serializers import UserSerializer
User = get_user_model()
logger = logging.getLogger('logzio')
class SendCodeView(ModelViewSet):
queryset = VerificationSMSCode.objects.all()
serializer_class = SendCodeSerializer
permission_classes = (AllowAny, )
def post(self, request, **kwargs):
print('DEBUG ' + request.data)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
logger.info(f'send code log', extra=request.data)
VerificationSMSCode.create(serializer.user)
return Response(status=status.HTTP_204_NO_CONTENT)
models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from auth2.utils import get_random_code
from core.models import User
class VerificationSMSCode(models.Model):
STATUS_PENDING = 'pending'
STATUS_DELIVERED = 'delivered'
STATUS_ON_THE_WAY = 'on_the_way'
user = models.ForeignKey('core.User', related_name='verification_sms_codes', on_delete=models.CASCADE)
code = models.IntegerField(default=get_random_code)
created_at = models.DateTimeField(_("Created"), auto_now_add=True)
code_sent_at = models.DateTimeField(null=True, blank=True)
code_sent_error = models.TextField(blank=True)
sms_id = models.CharField(max_length=200, blank=True)
sms_status = models.CharField(default=STATUS_ON_THE_WAY, max_length=200, blank=True)
delivered_at = models.DateTimeField(null=True, blank=True)
code_used_at = models.DateTimeField(null=True, blank=True)
#classmethod
def create(cls, user):
old_code = cls.objects.filter(user=user, phone=user.phone, code_used_at__isnull=True)
if old_code:
old_code.update(code_sent_at=None)
return old_code.first()
else:
obj = cls.objects.create(user=user, phone=user.phone)
return obj
serializers.py
from rest_framework import serializers
from auth2.api import consts
from auth2.models import VerificationSMSCode
from chat.models import Chat
from core.models import User
class SendCodeSerializer(serializers.Serializer):
phone = serializers.IntegerField()
default_error_messages = {
"invalid_credentials": consts.INVALID_CREDENTIALS_ERROR,
"inactive_account": consts.INACTIVE_ACCOUNT_ERROR,
"invalid_code": consts.INVALID_CODE_ERROR,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
def validate(self, attrs):
self.user, user_created = User.objects.get_or_create(phone=attrs['phone'])
if user_created:
chat = Chat.objects.create(title='Поддержка')
chat.users.add(self.user)
support_user = User.objects.filter(is_support=True).first()
if support_user:
chat.users.add(support_user)
if not self.user.is_active:
self.fail('inactive_account')
return attrs
def create(self, validated_data):
return VerificationSMSCode.objects.create(**validated_data)
I am trying to send a phone number which is where I'm sending random 4-digit code to and it fails.
If you have any ideas about how to fix this, please share.
UPD1
Here is the full Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/auth/code_send/
Django Version: 2.2.12
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'drf_yasg',
'mptt',
'django_mptt_admin',
'django_extensions',
'auth2',
'bcard',
'chat',
'core',
'filestorage',
'ckeditor',
'fcm_django',
'dbbackup']
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',
'core.middleware.RequestLoggerMiddleware',
'core.middleware.UpdateLastOnlineMiddleware']
Traceback:
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\viewsets.py" in view
114. return self.dispatch(request, *args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
505. response = self.handle_exception(exc)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception
476. raise exc
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\mixins.py" in create
19. self.perform_create(serializer)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\mixins.py" in perform_create
24. serializer.save()
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\serializers.py" in save
212. self.instance = self.create(validated_data)
File "D:\Projects\backend\auth2\api\serializers.py" in create
39. return VerificationSMSCode.objects.create(**validated_data)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\query.py" in create
420. obj = self.model(**kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\base.py" in __init__
501. raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
Exception Type: TypeError at /api/auth/code_send/
Exception Value: VerificationSMSCode() got an unexpected keyword argument 'phone'

Related

FileNotFoundError: [WinError 3] The system cannot find the path specified: ''

I get this error when Ii execute runserver and I try to access the API:
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
I check imports, models, serializer, viewsets and URLs. I don't know what does it means?
Here you have a screenshot of the error:
I get that exception when I go to: http://127.0.0.1:8000/api/v1.0/notes/
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1.0/notes/
Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'note',
'rest_framework']
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']
The traceback is:
Traceback:
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\base.py" in _get_response
143. response = response.render()
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\response.py" in rendered_content
70. ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in render
725. context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in get_context
656. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
564. data = serializer.data.copy()
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in data
559. ret = super().data
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in data
265. self._data = self.get_initial()
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in get_initial
409. for field in self.fields.values()
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\utils\functional.py" in __get__
80. res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in fields
360. for key, value in self.get_fields().items():
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in get_fields
1056. fields[field_name] = field_class(**field_kwargs)
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\fields.py" in __init__
1503. allow_folders=allow_folders, required=required
File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\forms\fields.py" in __init__
1109. for f in os.scandir(self.path):
Exception Type: FileNotFoundError at /api/v1.0/notes/
Exception Value: [WinError 3] El sistema no puede encontrar la ruta especificada: ''
serializer.py
from .models import Note
from rest_framework import serializers
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Note
fields = '__all__'
viewsets.py
from rest_framework import viewsets
from .models import Note
from .serializer import NoteSerializer
class NoteViewSet(viewsets.ModelViewSet):
queryset = Note.objects.all()
serializer_class = NoteSerializer
urls.py
from rest_framework import routers
from .viewsets import NoteViewSet
router = routers.SimpleRouter()
router.register('notes', NoteViewSet)
urlpatterns = router.urls
Problem was in models.py, I have a FilePathField.
Thanks #IşıkKaplan
from django.db import models
# Create your models here.
class Note(models.Model):
date = models.DateTimeField()
endDate = models.DateTimeField()
note = models.TextField()
attachment = models.CharField(max_length=50)
task = models.BooleanField()
tag = models.CharField(max_length=50)
type = models.CharField(max_length=50)

Keep getting "IntegrityError FOREIGN KEY constraint failed" when i am trying to delete a post

Every time i try to delete a post i keeping getting this error, but my delete button use to work before.
I think it has something to do with the on_delete attribute but i changed its value a few times and it still did not work.
//models.py
from django.db import models
from django.conf import settings
from django.urls import reverse
User = settings.AUTH_USER_MODEL
class PostManager(models.Manager):
def search(self, query):
qs = self.get_queryset().filter(title__icontains=query)
if qs:
return qs
return None
def get_by_id(self, id):
qs = self.get_queryset().filter(id=id)
if qs.count() == 1:
return qs.first()
else:
return None
# Create your models here.
class PostModel(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
message = models.TextField()
date = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
def __str__(self):
return self.title
objects = PostManager()
def get_total_likes(self):
return self.likes.count()
def get_absolute_url(self):
return reverse("birdpost:detail", kwargs={"id": self.id})
def get_like_url(self):
return reverse("birdpost:like-toggle", kwargs={"id": self.id})
def get_delete_url(self):
return reverse("birdpost:delete_post", kwargs={"id": self.id})
//views.py
def del_post(request, id):
obj = get_object_or_404(PostModel, id=id)
if request.user != obj.user:
print("Ooh no looks like this post is not yours... ")
else:
obj.delete()
return redirect("home")
Environment:
Request Method: GET
Request URL: http://localhost:8000/post/4/delete
Django Version: 2.2.1
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'birdpost',
'search']
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 "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
240. return self.connection.commit()
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/grey/Desktop/python/birds/src/birdpost/views.py" in del_post
104. obj.delete()
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/models/base.py" in delete
919. return collector.delete()
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/models/deletion.py" in delete
318. sender=model, instance=obj, using=self.using
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/transaction.py" in __exit__
240. connection.commit()
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in commit
262. self._commit()
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
240. return self.connection.commit()
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
240. return self.connection.commit()
Exception Type: IntegrityError at /post/4/delete
Exception Value: FOREIGN KEY constraint failed
I removed the default=1 like #Na'aman Hirschfeld said, and deleted all of my migrations and my database. And now it's working fine.
Try removing the default=1. I don't know if setting a default value without a choice field is the way to go.

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

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 the get_queryset() method.
get_queryset does not expect the request parameter, and it will not be passed by the DRF base class. It is however available as an instance attribute. You should remove it from the method signature and the super call, and access it via 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
As Sayse said, it only requires self. but you don't have to pass self to get_queryset(). self is just an instance, super itself is self-instance.
So just change your following line from
super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
to
super(FileUploaderViewSet, self).get_queryset()
look at the code snippet here
Update:
Are you sure, your get_queryset is in the same class?
Did you try just writing queryset = Model.objects.all()?
I do not see model = ModelName in your view.
view class should have following fields.
def get_queryset(self):
return queryset
serializer_class = SerializerClass
model = ModelName
get_queryset only requires self as a parameter.
Simply remove the other args.
The get_queryset() does not expect a 'request'. Maybe remove the 'request' argument from the get_queryset(). For reference you can check:
get_queryset()
Maybe something like this:
def get_queryset(self, *args, **kwargs):
qs = your_model.objects.all()
qs = qs.filter(owner=self.request.user)
return qs

Django REST Framework; Problems serializing User model with 'groups' field

I'm trying to add a REST framework to my existing project. However, whenever I add 'groups' to the fields in my UserSerializer class, I get this traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/users/
Django Version: 1.10.7
Python Version: 3.6.3
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'blended_learning_portal.users.apps.UsersConfig',
'blended_learning_portal.taskapp.celery.CeleryConfig',
'blended_learning_portal.unit.apps.UnitConfig',
'blended_learning_portal.data.apps.DataConfig',
'debug_toolbar',
'django_extensions',
'graphos',
'ckeditor',
'ckeditor_uploader',
'webpack_loader',
'rest_framework']
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',
'django.middleware.locale.LocaleMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
378. url = self.get_url(value, self.view_name, request, format)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in get_url
316. return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in reverse
50. url = _reverse(viewname, args, kwargs, request, format, **extra)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in _reverse
63. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
392. (lookup_view_s, args, kwargs, len(patterns), patterns)
During handling of the above exception (Reverse for 'group-detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []), another exception occurred:
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
90. return self.dispatch(request, *args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in data
738. ret = super(ListSerializer, self).data
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
656. self.child.to_representation(item) for item in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in <listcomp>
656. self.child.to_representation(item) for item in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
500. ret[field.field_name] = field.to_representation(attribute)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
520. for value in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in <listcomp>
520. for value in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
393. raise ImproperlyConfigured(msg % self.view_name)
Exception Type: ImproperlyConfigured at /api/users/
Exception Value: Could not resolve URL for hyperlinked relationship using view name "group-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
The error seems to be coming from the UserSerializer, not the GroupSerializer. It obviously doesn't know where to look for group-detail (since I have that in the namespace api_v1. I'm not sure how to specify that, however.
api/views.py:
from django.contrib.auth.models import Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
# We're using a modified User model
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
api/serializers.py:
from django.contrib.auth.models import Group
from rest_framework import serializers
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
extra_kwargs = {'url': {'view_name': 'api_v1:user-detail'}}
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
extra_kwargs = {'url': {'view_name': 'api_v1:group-detail'}}
model = Group
lookup_field = 'id'
fields = ('url', 'id', 'name')
api/urls.py:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
I expect it's just a matter of telling Django where to look for group-detail. Any help would be greatly appreciated, this is driving me crazy.
I guess I overlooked that you could add a kwarg samespace for each field. I'm a bit silly. Anyway, changing this in my serializers.py was the solution:
extra_kwargs = {
'url': {'view_name': 'api_v1:user-detail'},
# Added this line:
'groups': {'view_name': 'api_v1:group-detail'},
}
By the way, this is necessary because rest_framework.routers.DefaultRouter doesn't handle namespaces at all. See this issue on Git.

Error while serializing queryset object in Django Rest Framework

I am trying to serialize my queryset object and getting error as below,
Exception Type: AttributeError
Exception Value:
Got AttributeError when attempting to get a value for field `fullName` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'fullName'.
Traceback
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/user/crud/
Django Version: 1.9
Python Version: 2.7.10
Installed Applications:
['rest_framework',
'background_task',
'userApp',
'imageUpload',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch
466. response = self.handle_exception(exc)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "C:\Users\JpG\Desktop\CYC_Heroku\userApp\views.py" in create
24. return Response(data=serializer.data) # {"detail": "Mobile Number already exist"})
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data
503. ret = super(Serializer, self).data
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\fields.py" in get_attribute
422. raise type(exc)(msg)
Exception Type: AttributeError at /user/crud/
Exception Value: Got AttributeError when attempting to get a value for field `fullName` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'fullName'.
I'm including some code snippet here .
views.py
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
mobNum = request.data.get('mobileNum')
if UserModel.objects.filter(mobileNum=mobNum).exists():
serializer=UserSerializer(UserModel.objects.filter(mobileNum=mobNum))
return Response(data=serializer.data)
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = '__all__'
models.py
class UserModel(models.Model):
fullName = models.CharField(max_length=100)
mobileNum = models.CharField(max_length=12)
isAuthority = models.BooleanField(default=False)
My sample Input
Actually, I am expecting an output similar to the output of below code
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data)
try get() instead of filter()
That is, serializer=UserSerializer(UserModel.objects.get(mobileNum=mobNum))
Full views.py
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
mobNum = request.data.get('mobileNum')
if UserModel.objects.filter(mobileNum=mobNum).exists():
serializer=UserSerializer(UserModel.objects.get(mobileNum=mobNum))
return Response(data=serializer.data)

Categories

Resources