一、在settings中设置media

  1. # settings.py
  2. import os
  3. from pathlib import Path
  4. BASE_DIR = Path(__file__).resolve().parent.parent
  5. MEDIA_URL = '/media/'
  6. MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

二、在项目总的路由下添加图片路由

  1. # urls.py
  2. from django.urls import path, re_path
  3. from django.conf.urls.static import serve
  4. from 项目 import settings
  5. urlpatterns = [
  6. re_path(r"^media/(?P<path>.*)$", serve, {'document_root': settings.MEDIA_ROOT})
  7. ]
  8. # 注意: 必须加上$结尾

三、在创建序列化器

  1. #serializers.py
  2. from rest_framework import serializers
  3. class ProductListSerializers(serializers.Serializer):
  4. """
  5. 商品
  6. """
  7. ...
  8. products_front_image = serializers.ImageField(required=True, use_url=True)
  9. # 在序列化器中的ImageField字段添加上use_url=True,使用url

四、在views文件中调用序列化器

  1. # views.py
  2. from .models import Products
  3. from rest_framework.views import APIView
  4. from rest_framework.response import Response
  5. class ProductsList(APIView):
  6. def get(self, request, *args, **kwargs):
  7. key_id = request.GET.get('id')
  8. print(key_id)
  9. products = Products.objects.filter(id=key_id)
  10. serializers = ProductListSerializers(products,
  11. many=True,
  12. context={"request": request})
  13. return Response(serializers.data)
  14. # 在调用序列化器时传入参数context={"request": request},如果想要图片加上url,必须传入该参数
  15. '''请求结果'''
  16. [
  17. {
  18. "name": "自营高档茶叶礼盒定制款(包邮)",
  19. "description": "高档商品",
  20. "click_num": 0,
  21. "sold_num": 0,
  22. "fav_num": 0,
  23. "products_num": 0,
  24. "market_price": 598.0,
  25. "shop_price": 299.0,
  26. "products_front_image": "http://localhost:8000/media/products/tea-gift-customized01.png"
  27. }
  28. ]