【问题标题】:Django rest framework and CloudinaryDjango rest 框架和 Cloudinary
【发布时间】:2018-06-12 15:03:08
【问题描述】:

为什么我在尝试上传新图片时收到此错误响应:[02/Jan/2018 22:05:11] "POST /api/v1/images/ HTTP/1.1" 400 43。

{ "error": "不是一个有效的字符串。" }

我在 Django 世界中是全新的,并尝试遵循教程,但由于某种原因,我的代码不起作用,我尝试调试我的代码,但我不明白为什么它对我不起作用。

这是我的模特

from django.db import models
from core.models import TimestampedModel

class Image(TimestampedModel):
    image = models.CharField(max_length=350)

    def __str__(self):
        return self.image

这是我的看法

from random import randint
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser
from cloudinary.templatetags import cloudinary
from .serializers import ImageSerializer
from .models import Image


class ImageCloud(APIView):
    parser_classes = (MultiPartParser, FormParser,)
    serializer_class = ImageSerializer

    def get(self, request, format=None):
        images = Image.objects.all()
        serializer = ImageSerializer(images, many=True)
        return Response ({'images': serializer.data}, status=status.HTTP_200_OK)

    def upload_image_cloudinary(self, request, image_name):
        cloudinary.uploader.upload(
            request.FILES['image'],
            public_id=image_name,
            crop='limit',
            width='2000',
            height='2000',
            eager=[
                {'width': 200, 'height': 200,
                  'crop': 'thumb', 'gravity ': 'auto',
                  'radius': 20, 'effect': 'sepia'},
                {'width': 100, 'height': 150,
                 'crop': 'fit', 'format ': 'png'}
            ],
            tags=['image_ad', 'NAPI']
        )

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            try:
                imageName = '{0}_v{1}'.format(request.FILES['image'].name.split('.')[0], randint(0, 100))
                self.upload_image_cloudinary(request, imageName)
                serializer.save(image_ad=imageName)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            except Exception:
                return Response({'image': 'Please upload a valid image'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            print(serializer)
            return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

这是我的序列化程序

from rest_framework import serializers
from cloudinary.templatetags import cloudinary
from django.contrib.humanize.templatetags.humanize import naturaltime
from .models import Image

class ImageSerializer(serializers.ModelSerializer):
    image = serializers.CharField(required=False)
    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    class Meta:
        model = Image
        fields = ('id', 'image', 'createdAt',)

    def to_representation(self, instance):
        representation = super(ImageSerializer, self).to_representation(instance)
        imageUrl = cloudinary.utils.cloudinary_url(
            instance.image, width=100, height=150, crop='fill')

        representation['image'] = imageUrl[0]
        representation['createdAt'] = naturaltime(instance.created)
        return representation


    def get_created_at(self, instance):
        return instance.created_at.isoformat()

【问题讨论】:

  • 使用 Imagefield 代替 CharField。
  • 嗨@Linovia 我已经按照你说的尝试过了,但现在传递给我在 if 中检查序列化程序数据是否有效的例外异常
  • 可能更好的解决方案是使用具有“图像”类型的 CloudinaryField。您可以在模型上设置它并将所有选项传递给options dict。它需要更少的自定义代码,并且与 DRF/模型通常的工作方式一致。 Here 是该主题的文档

标签: django python-3.x api django-rest-framework cloudinary


【解决方案1】:

我确定您现在是专家,我认为您的 str 可能返回 None 字符串值,因此在您的 Image 类更改中

def __str__(self):
    return self.image

 def __str__(self):
        return str(self.image)

【讨论】:

    猜你喜欢
    • 2015-01-04
    • 2015-08-07
    • 2014-04-21
    • 2015-04-26
    • 2015-07-16
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多