如何在Django Rest框架中修复ImageField上传?

时间:2019-01-11 12:14:19

标签: django django-rest-framework

我正在尝试将个人资料图片上传到媒体文件夹,尽管这在django admin Web界面上运行良好,但它不是从api端点上传的,它为媒体根提供了图片名称,但我无法访问该图像也不在get_upload_path方法所指向的位置。任何帮助将不胜感激。

settings.py:

MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media")

编辑:

型号:

def get_upload_path(instance, filename): return 'grey/{0}/{1}'.format(instance.category_name, filename)

class Category(models.Model): icon_url_greyscale = models.ImageField( upload_to=get_upload_path, null=True, blank=True)

serializer.py:

class CategoryCreateSerializer(serializers.ModelSerializer): def create(self, validated_data): cat = Category.objects.create(**validated_data)

views.py:

class CategoryCreateAPIView(APIView): permission_classes = (IsAdminUser,) serializer_class = CategoryCreateSerializer

`def post(self, request):
    data = request.data
    print(data)
    serializer = self.serializer_class(data=data)
    if serializer.is_valid():
        serializer.save()
        return Response({'status':True, 'message':'category created'}, status=status.HTTP_201_CREATED)
    else:
        raise CustomException(detail="Could not create category", status_code=status.HTTP_400_BAD_REQUEST)`

这是预期的结果: '“ http://127.0.0.1:8000/media/profile_photo/aafaaaaaa2a%40gmail.com/lol.jpg”'

这就是所得到的:

http://127.0.0.1:8000/media/test.jpg

0 个答案:

没有答案