我有一个 Django REST Framework 项目,它使用ModelViewSet
为包含FileField
.
我在这里分享了一个演示这个问题的 Django 项目的完整示例。但总结一下关键组件:
模型.py
from django.db import models
class Profile(models.Model):
image = models.FileField(upload_to='uploads/%Y/%m/%d/')
视图.py
from rest_framework import (
viewsets,
serializers,
parsers,
)
from sample import models
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = models.Profile
fields = ['id', 'image']
read_only_fields = ['id']
class ProfileViewSet(viewsets.ModelViewSet):
serializer_class = ProfileSerializer
queryset = models.Profile.objects.all()
网址.py
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularSwaggerView,
)
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework.routers import DefaultRouter
from sample import views
router = DefaultRouter()
router.register('profile', views.ProfileViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
path(
'api/docs/',
SpectacularSwaggerView.as_view(url_name='api-schema'),
name='api-docs',
),
path('', include(router.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py(REST_FRAMEWORK
仅配置):
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
要求.txt
Django==3.2.3
djangorestframework==3.12.4
drf-spectacular==0.16.0
我正在使用drf-spectacular生成可浏览的 Swagger-UI 文档来记录 API。
问题是FileField
Swagger-UI 中的输入是string
输入,并且没有提供设置文件的选项:
我想要一个文件输入,我可以在其中选择一个将发送到 API 的文件。
我的问题是:如何配置 DRF 或 drf-spectacular 以显示该字段?