1

trying to create a function based post api

views.py:

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def post_blog(request):
    user = request.user
    data = request.data
    if data['image'] and len(data['image']) == 0:
        blog = Blog.objects.create(
            title=data['title'],
            description=data['description'],
            user=user
        )
    else:
        blog = Blog.objects.create(
            title=data['title'],
            description=data['description'],
            image=data['image'],
            user=user
        )

    serializer = BlogSerializer(blog)
    return Response(serializer.data)

models.py:

class Blog(models.Model):
    blog_id = models.AutoField(primary_key=True, editable=False)
    title = models.CharField(max_length=100, null=False)
    description = models.TextField(null=False)
    image = models.ImageField(null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

serializers.py:

class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ['blog_id', 'title','description', 'image', 'user', 'created_at']

after performing post request to "POST http://localhost:8000/api/blogs/post/" I am getting this error:

System check identified no issues (0 silenced).
June 15, 2021 - 01:54:10
Django version 3.2.4, using settings 'codersavvy.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /api/blogs/post/
Traceback (most recent call last):
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "D:\work environment\Django_Api\codersavvy\blog\views.py", line 75, in post_blog
    image=data['image'],
KeyError: 'image'
[15/Jun/2021 01:54:15] "POST /api/blogs/post/ HTTP/1.1" 500 96879

/It looks like your post is mostly code; please add some more details. no more details to add/

techedifice
  • 163
  • 1
  • 11

1 Answers1

1

You need to check if the image is in the data, so:

if 'image' in data and not data['image']:
    # …

You likely want to rewrite that to:

if 'image' not in data or not data['image']:
    # …
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • thanks for help. but solution not working. problem remains the same, – techedifice Jun 14 '21 at 19:56
  • 1
    @techedifice: please edit the question and share the *full* traceback. – Willem Van Onsem Jun 14 '21 at 19:57
  • 1
    @techedifice: but that is due to the `image=data['image']` in the `else`: the `else` will "fire" if `'image'` is *not* in `data`, or it has a length greater than 0, you likely wanted to use `or`. – Willem Van Onsem Jun 14 '21 at 20:01
  • 1
    @techedifice: likely what you wanted to check was that of the second code fragment: to capture the case where `image` is *not* part of the `data`, or if it is, that it has a zero length. – Willem Van Onsem Jun 14 '21 at 20:03
  • 1
    thanks for your kind help. I reversed the if else statement and it worked. you have been a great help today. – techedifice Jun 14 '21 at 20:07