Home > database >  AttributeError: 'WSGIRequest' object has no attribute 'get' heroku
AttributeError: 'WSGIRequest' object has no attribute 'get' heroku

Time:10-28

Am having a get request but it's failing on heroku with this error :

AttributeError: 'WSGIRequest' object has no attribute 'get'

I have failed to get the root cause of it Below is my view :

class PostDetail(generics.GenericAPIView):
    """Blog post details"""
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer
    authentication_classes = (JWTAuthentication,)
    permission_classes = (PostsProtectOrReadOnly, IsMentorOnly,)
    lookup_field = 'slug'

    def get_post_object(self, slug):
        post = get_blog_by_slug(slug)
        return post

    def get(self, request, slug):
        post = self.get_post_object(slug)
        if not post:
            return response.Response({
                'errors': _('Sorry, Blog post with the specified slug does'
                            'not exist')
            }, status=status.HTTP_404_NOT_FOUND)

        # track views of a viewed blog post.
        ip_address = get_ip_address(request)
        obj = CustomIPAddress.objects.create(address=ip_address)
        post.address_views.add(obj)

        serializer = self.serializer_class(post, context=request)
        return response.Response(serializer.data, status=status.HTTP_200_OK)

Methods am calling above :

def get_blog_by_slug(slug: str):
    """Get post by slug."""
    try:
        obj = Post.objects.get(slug=slug)
        return obj
    except Post.DoesNotExist:
        return None

def get_ip_address(request):
    """get ip address."""
    try:
        client_ip, is_routable = get_client_ip(request)
        if client_ip is None:
            return uuid.uuid4()
        else:
            return client_ip
    except AttributeError:
        return uuid.uuid4()
    except:
        return uuid.uuid4()

Am wondering why on local it's working but on heroku server am getting this error.

EDIT :

Serializers are as below :

class PostSerializer(serializers.ModelSerializer):
    """Post Serializer"""
    owner = UserProfile(read_only=True)
    tags = TagSerializer(many=True)
    comments = CommentSerializer(many=True, read_only=True)
    slug = serializers.SlugField(read_only=True)

    class Meta:
        model = Post
        fields = ('id', 'title', 'body', 'owner', 'slug',
                  'comments', 'tags', 'description', 'image', 'bookmarks',
                  'created', 'modified', 'blog_views', 'blog_likes',
                  'read_time',)

    def create(self, validated_data):
        """Create a blog post in a customized way."""
        tags = validated_data.pop('tags', [])
        post = Post.objects.create(**validated_data,
                                   owner=self.context.user)
        for tag in tags:
            tag_qs = Tag.objects.filter(name__iexact=tag.get('name'))
            if tag_qs.exists():
                tag_obj = tag_qs.first()
            else:
                tag_obj = Tag.objects.create(
                    name=tag.get('name'),
                    owner=self.context.user, )
            post.tags.add(tag_obj)

        return post

    def update(self, instance, validated_data):
        """Update blog posts."""
        tags = validated_data.pop('tags', [])
        instance = super(PostSerializer, self).update(instance, validated_data)

        if len(tags):
            for tag in tags:
                tag_qs = Tag.objects.filter(name__iexact=tag.get('name'))
                if tag_qs.exists():
                    tag = tag_qs.first()
                else:
                    tag = Tag.objects.create(name=tag.get('name'),
                                             owner=self.context.user, )
                instance.tags.clear()
                instance.tags.add(tag)

        return instance

Full logs from heroku :

2021-10-27T19:51:08.300812 00:00 app[web.1]: Internal Server Error: /api/v1/blogs/posts/logical-designs-2021-10-23-180259622506-06419c8c-6eee-4cd0-a328-78f3735700ee/
2021-10-27T19:51:08.300822 00:00 app[web.1]: Traceback (most recent call last):
2021-10-27T19:51:08.300823 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/request.py", line 409, in __getattr__
2021-10-27T19:51:08.300823 00:00 app[web.1]: return getattr(self._request, attr)
2021-10-27T19:51:08.300824 00:00 app[web.1]: AttributeError: 'WSGIRequest' object has no attribute 'get'
2021-10-27T19:51:08.300824 00:00 app[web.1]: 
2021-10-27T19:51:08.300825 00:00 app[web.1]: During handling of the above exception, another exception occurred:
2021-10-27T19:51:08.300825 00:00 app[web.1]: 
2021-10-27T19:51:08.300825 00:00 app[web.1]: Traceback (most recent call last):
2021-10-27T19:51:08.300826 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
2021-10-27T19:51:08.300826 00:00 app[web.1]: response = get_response(request)
2021-10-27T19:51:08.300826 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
2021-10-27T19:51:08.300827 00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs)
2021-10-27T19:51:08.300827 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback
2021-10-27T19:51:08.300828 00:00 app[web.1]: return callback(request, *args, **kwargs)
2021-10-27T19:51:08.300828 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
2021-10-27T19:51:08.300828 00:00 app[web.1]: return view_func(*args, **kwargs)
2021-10-27T19:51:08.300829 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 73, in view
2021-10-27T19:51:08.300829 00:00 app[web.1]: return self.dispatch(request, *args, **kwargs)
2021-10-27T19:51:08.300829 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py", line 505, in dispatch
2021-10-27T19:51:08.300829 00:00 app[web.1]: response = self.handle_exception(exc)
2021-10-27T19:51:08.300830 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py", line 465, in handle_exception
2021-10-27T19:51:08.300830 00:00 app[web.1]: self.raise_uncaught_exception(exc)
2021-10-27T19:51:08.300830 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
2021-10-27T19:51:08.300831 00:00 app[web.1]: raise exc
2021-10-27T19:51:08.300831 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/views.py", line 502, in dispatch
2021-10-27T19:51:08.300831 00:00 app[web.1]: response = handler(request, *args, **kwargs)
2021-10-27T19:51:08.300832 00:00 app[web.1]: File "/app/blog/views.py", line 56, in get
2021-10-27T19:51:08.300832 00:00 app[web.1]: return response.Response(serializer.data, status=status.HTTP_200_OK)
2021-10-27T19:51:08.300832 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 562, in data
2021-10-27T19:51:08.300833 00:00 app[web.1]: ret = super().data
2021-10-27T19:51:08.300833 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 260, in data
2021-10-27T19:51:08.300834 00:00 app[web.1]: self._data = self.to_representation(self.instance)
2021-10-27T19:51:08.300834 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 529, in to_representation
2021-10-27T19:51:08.300834 00:00 app[web.1]: ret[field.field_name] = field.to_representation(attribute)
2021-10-27T19:51:08.300835 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 677, in to_representation
2021-10-27T19:51:08.300835 00:00 app[web.1]: return [
2021-10-27T19:51:08.300835 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 678, in <listcomp>
2021-10-27T19:51:08.300836 00:00 app[web.1]: self.child.to_representation(item) for item in iterable
2021-10-27T19:51:08.300836 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 529, in to_representation
2021-10-27T19:51:08.300836 00:00 app[web.1]: ret[field.field_name] = field.to_representation(attribute)
2021-10-27T19:51:08.300837 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 529, in to_representation
2021-10-27T19:51:08.300837 00:00 app[web.1]: ret[field.field_name] = field.to_representation(attribute)
2021-10-27T19:51:08.300837 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/serializers.py", line 529, in to_representation
2021-10-27T19:51:08.300838 00:00 app[web.1]: ret[field.field_name] = field.to_representation(attribute)
2021-10-27T19:51:08.300838 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/fields.py", line 1586, in to_representation
2021-10-27T19:51:08.300838 00:00 app[web.1]: request = self.context.get('request', None)
2021-10-27T19:51:08.300839 00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rest_framework/request.py", line 411, in __getattr__
2021-10-27T19:51:08.300839 00:00 app[web.1]: return self.__getattribute__(attr)
2021-10-27T19:51:08.300839 00:00 app[web.1]: AttributeError: 'Request' object has no attribute 'get'

CodePudding user response:

You can not send the request directly as context=… to the serializer. The context should be a dictionary-like object.

What you can do is construct a dictionary where you map the request to the request, like:

serializer = self.serializer_class(post, context={'request': request })

Then you can use this as:

class PostSerializer(serializers.ModelSerializer):
    # ⋮

    def create(self, validated_data):
        """Create a blog post in a customized way."""
        tags = validated_data.pop('tags', [])
        post = Post.objects.create(**validated_data, owner=self.context['request'].user)
        # ⋮
  • Related