如何通过 POSTMAN 发送 'image'? (Django 图像字段)

How to send 'image' via POSTMAN? (Django Image Field)

我想像这样通过邮递员发送图片并保存到 'media' 目录,但不知道如何操作。

enter image description here

这些是我使用的代码。

  1. models.py

    class Article(models.Model):
    
         emotion = models.TextField()
         location = models.TextField()
         menu = models.TextField()
         weather = models.TextField()
         song = models.TextField()
         point = models.IntegerField()
         content = models.TextField()
    
         image = models.ImageField(default = 'media/coffee_default.jpg', upload_to = "%Y/%m/%d")
         user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
         created = models.DateTimeField(default = now)
         liked = models.BooleanField(default = False)
         num_liked = models.IntegerField(default = 0)
    
  2. views.py

@api_view(['POST']) @permission_classes([]) def post_articles(请求): 用户 = request.user 正文 = json.loads(request.body)

article = Article(
    emotion = body['emotion'],
    location = body['location'],
    menu = body['menu'],
    weather = body['weather'],
    image = body['image'],
    song = body['song'],
    point = body['point'],
    content = body['content'],
    user = user)
article.save()

serializers = ArticleSerializer(article)

return JsonResponse({ "success": True, "data": serializers.data })
  1. serializers.py

    class ArticleSerializer(serializers.ModelSerializer): class元: 型号 = 文章 字段 = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image'、'user'、'created'、'liked'、'num_liked']

根据我的经验,您不需要对文件字段做任何特别的事情,只需告诉它使用文件字段即可:

from rest_framework import routers, serializers, viewsets

class Article(django.db.models.Model):
    image = django.db.models.ImageField()
# rest of fields are excluded --TODO

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = ('id', 
                 'image', # <-- HERE
                 'menu', 'weather', 'song', 'point', 'content', 'location', 'emotion')   

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = models.Article.objects.all()
    serializer_class = ArticleSerializer

router = routers.DefaultRouter()
router.register(r'photos', PhotoViewSet)

api_urlpatterns = ([
    url('', include(router.urls)),
], 'api')
urlpatterns += [
    url(r'^api/', include(api_urlpatterns)),
]

您已准备好上传文件:

curl -sS http://example.com/api/photos/ -F 'image=@/path/to/file' 为您的模型具有的每个额外字段添加 -F field=value。并且不要忘记添加身份验证。

dothttp

POST http://example.com/api/articles/ 
multipart(
    'image'< '<file to the path>',
    'emotion' < "emotion",
    'location' < "location",
    'menu' < "menu",
    'weather' < "weather",
    'image' < "image",
    'song' < "song",
    'point' < "point",
    'content' < "content"
)