5

I have a viewset API which getting Notification of User who get authenticate with Django JWT but I got error. Please take a look!

Viewset:

from api.notifications.models import Notification 
from rest_framework.generics import ( ListAPIView )
from api.notifications.serializers import ( NotificationListSerializer )
from api.pagination import NewFeedPagination
from rest_framework.permissions import AllowAny
from api.permissions import IsOwnerOrReadOnly

class NotificationListAPIView(ListAPIView):
    permission_classes = [AllowAny]
    serializer_class = NotificationListSerializer
    ordering_fields = 'date'

    def get_queryset(self, *args, **kwargs):
        queryset_list = Notification.objects.filter(to_user=self.request.user)
        return queryset_list

When Logged in and access URL, it's successfull. But It doesn't logged in, it came to error: int() argument must be a string or a number, not 'AnonymousUser'. How can I set up with AnonymousUser, URL will come to login page: localhost:8000/admin?

All Traceback Error: Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  489.             response = self.handle_exception(exc)

File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception
  449.             self.raise_uncaught_exception(exc)

File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  486.             response = handler(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\rest_framework\generics.py" in get
  201.         return self.list(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())

File "C:\Users\User\Desktop\FeedGit\backend\api\notifications\views.py" in get_queryset
  16.         queryset_list = Notification.objects.filter(to_user=self.request.user)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  782.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  800.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1261.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1287.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1217.             condition = lookup_class(lhs, value)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup
  112.                 self.rhs = target_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  962.         return int(value)

Exception Type: TypeError at /api/v1/notifications/
Exception Value: int() argument must be a string or a number, not 'AnonymousUser'
2
  • Could you please post the whole TraceBack error? Like from which file and what line number you get this error ? Commented Dec 18, 2017 at 11:46
  • Traceback done, bro! Commented Dec 18, 2017 at 11:52

3 Answers 3

4

as your error say:

Exception Value: int() argument must be a string or a number, not 'AnonymousUser'

This means to filter Notification you are passing complete user object instead pass id only so:

change this line and this will work

 16.         queryset_list = Notification.objects.filter(to_user=self.request.user.id)
Sign up to request clarification or add additional context in comments.

Comments

1

That error from Django is a bit misleading as discussed on this forum. The main issue here is that you try to filter based on user on a view that doesn't enforce user authentication.

There are two questions here, do you want to only fetch Notifications if the user is logged in? or Would yo want to just fetch all Notifications if they are not.

In the former case, set the permission class of your view to allow only authenticated users like so:

    permission_classes = [IsAuthenticated]

In the case of fetch all (or do something else) if not authenticated, just check the user's authentication status like so:

    def get_queryset(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            return Notification.objects.filter(to_user=self.request.user)
        else:
            return Notification.objects.all()

Comments

-1

Looks like you haven't set up DRF in your settings. Try the following (or choose settings as you wish) and see if it works:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.