在Django

时间:2018-06-27 10:05:01

标签: django django-rest-framework

model.py:

class Album(models.Model):{
    poster = models.ImageField upload_to='static/images/album/%Y/%m/%d')
}

serializer.py

class AlbumSerializer(serializers.ModelSerializer):
doc = DoctorSerializer()

class Meta:
    model = Album
    fields = '__all__'

setting.py

STATIC_URL = '/static/'
STATICFILES_DIRS=[ 
    os.path.join(BASE_DIR,'static')
]

views.py

class index(viewsets.ModelViewSet):
    serializer_class = AlbumSerializer    
    queryset = Album.objects.all()

当我在http://127.0.0.1:8008/admin/qa/album/下上传图像时,该图像在数据库的发布者字段中显示为“ static / images / album / 2018/06/27 / xxxxxx.jpg”。而且我可以通过http://127.0.0.1:8008/static/images/album/2018/06/27/xxxxxx.jpg访问该图像。

但是,在索引视图中,Django Rest Framework API返回图像的url为: http://127.0.0.1:8008/api/index/static/images/album/2018/06/27/xxxxxx.jpg,使图像变为404。

为什么/ api / index /已添加到网址中?我的设定怎么了?需要您的帮助...

1 个答案:

答案 0 :(得分:2)

要正确提供媒体文件,您还需要在设置中添加MEDIA_URLMEDIA_ROOT

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

请注意,如果您在static路径中使用MEDIA_ROOT设置来设置upload_to目录,则可以跳过static

poster = models.ImageField(upload_to='images/album/%Y/%m/%d')

urls.py中:

from django.conf import settings

urlpatterns = [
    # your urls here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

UPD

正如@brunodesthuilliers在评论中所说,最好将媒体和静态文件分开,并使用media的URL和目录而不是static

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