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)
Related
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 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
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'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.
I am trying to get the UUIDField to work in python django using the following model:
class Ticket(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50)
However when I try adding an instance of the model to the database it returns the following error:
TypeError at /tickets/
coercing to Unicode: need string or buffer, UUID found
The documentation of UUIDField is really short and doesn't really help me.
edit: I did import uuid and here is the full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/tickets/
Django Version: 1.8.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'events',
'rest_framework')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
663. ret = super(ListSerializer, self).data
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
228. self._data = self.to_representation(self.instance)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
603. self.child.to_representation(item) for item in iterable
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
461. ret[field.field_name] = field.to_representation(attribute)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in to_representation
356. name = self.get_name(value)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in get_name
276. return six.text_type(obj)
Exception Type: TypeError at /tickets/
Exception Value: coercing to Unicode: need string or buffer, UUID found
Edit 2: My serializer looks like this:
class TicketSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticket
fields = ('url', 'id', 'name')
Edit 3:
I found the error. I made a mistake in my model. My unicode looked like this:
def __unicode__(self):
return self.id
And of course this does not work.
Probably you should use something like this:
def __unicode__(self):
return str(self.id)