[英]Django rest framework and Cloudinary
Why have I got this error response: [02/Jan/2018 22:05:11] "POST /api/v1/images/ HTTP/1.1" 400 43 when I try to upload a new image.为什么我收到此错误响应:[02/Jan/2018 22:05:11] "POST /api/v1/images/ HTTP/1.1" 400 43 当我尝试上传新图像时。
{ "error": "Not a valid string." { “错误”:“不是有效的字符串。” } }
I completely new in Django world and a try to follow a tutorial but for some reason, my code didn't work and I try to debug my code but I can't understand why it does not work for me.我在 Django 世界中是全新的,并尝试按照教程进行操作,但由于某种原因,我的代码不起作用,我尝试调试我的代码,但我不明白为什么它对我不起作用。
This my model这是我的 model
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
this my view这是我的看法
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)
this my serializer这是我的序列化程序
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()
I'm sure you are now an expert, I think your str migth have return a None string value so in your Image class change我确定您现在是专家,我认为您的str migth 返回了 None 字符串值,因此在您的图像 class 中更改
def __str__(self):
return self.image
to到
def __str__(self):
return str(self.image)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.