在DRF中优雅的上传图片

0 首先修改setting

修改setting.py

1
2
MEDIA_URL = ‘/media/‘
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

指定上传的媒体保存的地址
这个时候 上传的所有图片都会保存在根目录的media文件夹中

1 设置字段

myapp/model.py
中设置 指定imageField字段

1
2
3
4
5
6
7
from django.db import models
class Notice(models.Model):
text = models.TextField()
image = models.ImageField(
max_length=254,
blank=True,
)

2 serializer

myapp/serializer.py

1
2
3
4
5
6
from rest_framework.serializers import ModelSerializer
from myapp.models import User, Notice
class NoticeSerializer(ModelSerializer):
class Meta:
model = Notice
fields = ‘__all__’

3 ViewSet

In myapp/view.py

1
2
3
4
5
6
7
from rest_framework.viewsets import ModelViewSet
from core.serializers import Notice, NoticeSerializer
from rest_framework.parsers import MultiPartParser
class NoticeViewSet(ModelViewSet):
parser_classes = [MultiPartParser]
serializer_class = NoticeSerializer
queryset = Notice.objects.all()

4 设置 route

myapp/urls.py

1
2
3
4
5
6
from rest_framework.routers import DefaultRouter
from myapp.views import NoticeViewSet

routes = DefaultRouter()
routes.register(‘notice’, NoticeViewSet)
urlpatterns = routes.urls

5 设定 Media Url

urls.py

1
2
3
4
5
6
7
8
9
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘api/‘, include(’myapp.urls’))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

测试

直接访问对应url drf会给出测试页面

备注

在生产环境下 需要用nginx等进行静态资源的提供 不能直接用Django自带的服务器进行提供静态资源