1

试图创建一个基于函数的 post api

视图.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)

模型.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

序列化程序.py:

class BlogSerializer(serializers.ModelSerializer):

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

在对“POST http://localhost:8000/api/blogs/post/”执行发布请求后,我收到此错误:

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

/看起来你的帖子主要是代码;请添加更多细节。没有更多细节要添加/

4

1 回答 1

1

您需要检查 是否image在 中data,因此:

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

您可能希望将其重写为:

if 'image' not in data or not data['image']:
    # …
于 2021-06-14T19:47:33.143 回答