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
Related
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'
I have the following model:
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000)
cvfile = models.FileField()
I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed.
Should I have a function that the form calls to perform this? If so how can this be done?
def writeCV(self):
get_text = cvfile.open().read()
#write to cv field somehow
return self.cv
I am using django 1.9
Traceback from Messaoud's answer:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/cleaner/clean/add/
Django Version: 1.9
Python Version: 3.6.4
Installed Applications:
['cleaner.apps.CleanerConfig',
'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:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
255. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
221. return self.form_valid(form)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in form_valid
200. self.object = form.save()
File "C:\Python\Python36-32\lib\site-packages\django\forms\models.py" in save
451. self.instance.save()
File "C:\Users\barry\Desktop\College\Year 4\Semester 2\cvCleaner\cvcleaner\cleaner\models.py" in save
11. get_text = self.cvfile.open().read()
Exception Type: AttributeError at /cleaner/clean/add/
Exception Value: 'NoneType' object has no attribute 'read'
You can do this by overriding save method in your Model
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000, blank = True, null = True)
cvfile = models.FileField()
def save(self, *args, **kwargs):
get_text = self.cvfile.open().read()
self.cv = get_text
super(Clean, self).save(*args, **kwargs) # Call the "real" save() method.
Or by Using post_save signal
def writeCV(sender, instance, **kwargs):
get_text = instance.cvfile.open().read()
instance.cv = get_text
instance.save()
post_save.connect(writeCV, sender=Clean)
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.
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)
I'm building a reservation app with Django and I want to allow users to use one reservation as template for another. My idea is that I add ?prefill=<reservation_id> to url and then prefill empty form with data from reservation in prefill id.
My CreateView looks like this:
class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_context_data(self, **kwargs):
ctx = super(ReservationCreateView, self).get_context_data()
r = Reservation.objects.filter(pk=self.request.GET.get('prefill'))
ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
return ctx
This gives me: dictionary update sequence element #0 has length 30; 2 is required
Error stack:
Environment:
Request Method: GET
Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4
Django Version: 1.10.3
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'tags',
'profiles',
'reservations',
'drivers',
'import_export',
'src',
'crispy_forms',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'anymail',
'wf',
'storages',
'djangoformsetjs']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'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',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware']
Traceback:
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get
68. route_formset=route_formset))
File "/Users/jhotujec/Documents/projects/optilimo/reservations/views.py" in get_context_data
108. ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/forms.py" in __init__
30. super(ReservationForm, self).__init__(*args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/forms/models.py" in __init__
285. object_data.update(initial)
Exception Type: ValueError at /r/create/
Exception Value: dictionary update sequence element #0 has length 30; 2 is required
filter() always returns a queryset, and values() is then basically a list of dicts, whereas the form is expecting a single dict.
You could fix this by using r.values()[0] instead, but this is really the wrong approach. This is a model form; you should populate it by passing an actual model instance as the instance argument.
The problem is initial=r.values() where r is a QuerySet. values returns a list of dicts, initial expects a dict. You could get the Reservation instance and use the instance parameter of the form constructor instead:
# first() will return None if the QS is empty
r = Reservation.objects.get(pk=self.request.GET.get('prefill')).first()
ctx['form'] = ReservationForm(instance=r, request=self.request)