TypeError while using django rest framework tutorial

17,938

Solution 1

As pointed out by Daniel above, i had this stupid snippet in the settings file, which was causing the problem,

#REST_FRAMEWORK = {
#   '''Use hyperlinked styles by default'''
#   '''only used if serializer_class attribute is not set on a view'''
#   'DEFAULT_MODEL_SERIALIZER_CLASS':
#         'rest_framkework.serializers.HyperLinkedModelSerializer',
#   'DEFAULT_PERMISSION_CLASSES':
#          'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
# }

Commmented this and it worked.

Solution 2

Just to let others know, I kept getting this same error and found that I forgot to include a comma in my REST_FRAMEWORK. I had this:

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated'
),

instead of this:

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),

The comma defines this as a one-element tuple

Solution 3

In my case the typo was in views.py. Instead of ...

permission_classes = (permissions.IsAuthenticated,)

... I had ...

permission_classes = (permissions.IsAuthenticated)

Solution 4

I had the same error when I used custom permissions, because of a 'typo'

I had:

@permission_classes(EventByFacilityPermissions)
class EventByFacilityViewSet(viewsets.ModelViewSet):

instead of:

@permission_classes((EventByFacilityPermissions,))
class EventByFacilityViewSet(viewsets.ModelViewSet):

Solution 5

Pass the authentication class inside your class instead of in your settings.py if you need authentication just in some classes, and do like this:

authentication_classes = [TokenAuthentication, ]

instead of like this:

authentication_classes = TokenAuthentication
Share:
17,938
Sirius
Author by

Sirius

Astute technology enthusiast with more than 5 years of rich professional experience in analyzing requirements, writing software, while meeting superior quality checks and deadlines Expert skills in Python and Django/Flask framework with experience in end to end development and deployment Responsible for gathering stringent requirements, designing specifications and programming software that execute functionalities; extensive experience in web-frameworks Skilled in working in a cohesive unit to achieve software goals and extremely enthusiastic in planning work and modularizing responsibilities to achieve scheduled software deliveries MS in Advanced Software Engineering from the University of Sheffield, UK and B.E. (CS) from Maharashtra, India Linkedin Profile

Updated on June 07, 2022

Comments

  • Sirius
    Sirius almost 2 years

    I am new to using Django Rest framework, i am following this tutorial Django-Rest-Framework

    Instead of snippets my model consists of a userprofile as given below:

    class UserProfile(models.Model):
          user = models.OneToOneField(User)
          emp_code = models.CharField(max_length=10, blank=True)
          user_type = models.IntegerField(max_length=1, default=0, choices=USER_TYPE)
          group = models.ForeignKey(Group, null=True, blank=True)
          status = models.SmallIntegerField(max_length=1,default=0)
          added_on = models.DateTimeField(auto_now_add=True)
    

    The first part of the tutorial ran fine, got the desired output in json format as mentioned, however the second tutorial onwards i am getting type error:

    TypeError at /authentication/userprofile/
    'type' object is not iterable
    Request Method: GET
    Request URL:    http://*****.com/authentication/userprofile/
    Django Version: 1.6
    Exception Type: TypeError
    Exception Value:    
    'type' object is not iterable
    Exception Location: /home/web/cptm_venv/lib/python2.7/site-     packages/rest_framework/views.py in get_permissions, line 226
    Python Executable:  /usr/bin/python
    Python Version: 2.7.3
    Python Path:    
    ['/home/web/cptm_venv/lib/python2.7/site-packages',
     '/home/web/cptm',
     '/home/web/cptm_venv/lib/python2.7/site-packages',
     '/usr/lib/python2.7',
     '/usr/lib/python2.7/plat-linux2',
     '/usr/lib/python2.7/lib-tk',
     '/usr/lib/python2.7/lib-old',
     '/usr/lib/python2.7/lib-dynload',
     '/usr/local/lib/python2.7/dist-packages',
     '/usr/lib/python2.7/dist-packages',
     '/usr/lib/pymodules/python2.7']
     Server time:   Wed, 11 Dec 2013 17:33:54 +0530
     Traceback Switch to copy-and-paste view
    
    /home/web/cptm_venv/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
                    response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/django/views/generic/base.py in view
            return self.dispatch(request, *args, **kwargs) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/django/views/decorators/csrf.py in    wrapped_view
        return view_func(*args, **kwargs) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/rest_framework/views.py in dispatch
            response = self.handle_exception(exc) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/rest_framework/views.py in dispatch
            self.initial(request, *args, **kwargs) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/rest_framework/views.py in initial
        self.check_permissions(request) ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/rest_framework/views.py in   check_permissions
         for permission in self.get_permissions(): ...
    ▶ Local vars
    /home/web/cptm_venv/lib/python2.7/site-packages/rest_framework/views.py in get_permissions
        return [permission() for permission in self.permission_classes] ...
    ▶ Local vars
    

    The rest of the code is almost same as given in the above link in 2nd part and 3rd part: views.py

    from apps.authentication.models import UserProfile
    from apps.authentication.serializers import UserProfileSerializer
    from rest_framework import mixins
    from rest_framework import generics
    
    class UserProfileList(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
        queryset = UserProfile.objects.all()
        serializer_class = UserProfileSerializer
    
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            return self.create(request, *args, **kwargs)
    
    
    class UserProfileDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
        queryset = UserProfile.objects.all()
        serializer_class = UserProfileSerializer
    
        def get(self, request, *args, **kwargs):
            return self.retrieve(request, *args, **kwargs)
    
        def put(self, request, *args, **kwargs):
            return self.update(request, *args, **kwargs)
    
        def delete(self, request, *args, **kwargs):
            return self.destroy(request, *args, **kwargs)
    

    urls.py

    from django.conf.urls import patterns, url
    from rest_framework.urlpatterns import format_suffix_patterns
    from apps.authentication import views
    
    urlpatterns = patterns('',
        url(r'^userprofile/$', views.UserProfileList.as_view()),
        url(r'^userprofile/(?P<pk>[0-9]+)/$', views.UserProfileDetail.as_view()),
    )
    
    urlpatterns = format_suffix_patterns(urlpatterns)
    

    I am missing something very obvious, tried a lot to search what exactly the "type object not iterable" means in this context, and which object is causing the problem, but no luck. I am using Django Rest Framework version 2.3.

    Thanks in advance

    • Daniel Roseman
      Daniel Roseman over 10 years
      It seems that permission_classes is being set to None on your UserProfileList class. But that shouldn't happen with the code you show here, because it is set to api_settings.DEFAULT_PERMISSION_CLASSES in views.APIView, which generics.GenericAPIView inherits from. Have you overridden the settings anywhere?
    • Sirius
      Sirius over 10 years
      @DanielRoseman: Yup that was the problem, thanks a lot mate :), actually i followed quick tutorial in which there was this 'DEFAULT_PERMISSION_CLASSES': # 'rest_framework.permissions.DjangoModelPermissionsOrAnonRead‌​Only'. Commented this and it worked.
  • Keshav Agrawal
    Keshav Agrawal over 8 years
    You saved me lot of frustration!
  • Max Heiber
    Max Heiber over 8 years
    I think Python needs the trailing comma in order to recognize the expression as a 1-element tuple instead of just a regular expression in parentheses: wiki.python.org/moin/TupleSyntax
  • Rutwick Gangurde
    Rutwick Gangurde about 8 years
    Great! I removed that comma initially because I thought its a typo. Thanks for the tip!
  • Andrés Muñoz
    Andrés Muñoz about 7 years
    reading this is the more luckiest thing I have in a long time
  • MarkK
    MarkK about 7 years
    Thank you for this helped my a lot!
  • Harper
    Harper over 6 years
    I know commenting should not be used for thanking but... In this case a simple upvote is just not enough. ty!
  • Neil
    Neil almost 6 years
    Oh my. Principle of least surprise anyone?
  • davyria
    davyria over 5 years
    In my case, instead DEFAULT_PERMISION_CLASSES, the missing comma was in DEFAULT_AUTHENTICATION_CLASSES (with 1 element only). Thank you!