无法使用django rest框架在浏览器上显示图像

时间:2018-02-02 23:19:38

标签: python django rest django-models django-rest-framework

我遇到了类似于SO post的问题,但没有一个答案帮助我解决了我的问题。

我们是:我能够在服务器上保存图像,但无法从API图像超链接中获取图像。

我的档案:

model.py

class Summary(models.Model):

    question_text = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    cover_image = models.ImageField(upload_to='cover_image/', max_length=255)
    userProfileSummary = models.ManyToManyField(UserProfile, through='UserProfileSummary')

    def __str__(self):
        return self.question_text

views.py

class Summary(models.Model):

    question_text = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    cover_image = models.ImageField(upload_to='cover_image/', max_length=255)
    userProfileSummary = models.ManyToManyField(UserProfile, through='UserProfileSummary')

    def __str__(self):
        return self.question_text

serializer.py

class SummarySerializer(serializers.ModelSerializer):
    """A serializer for summary item"""
    cover_image = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model = models.Summary
        exclude = ('userProfileSummary',)

settings.py

STATIC_URL = '/static/'

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

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

urls.py

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from django.conf.urls.static import static
from django.conf import settings
from . import views

router = DefaultRouter()
router.register('Hello-viewset', views.HelloViewSet, base_name='hello-viewset')

urlpatterns= [
    path('hello-view/', views.HelloApiView.as_view()),
    path('UserProfileSummary/<int:id>/', views.UserProfileSummaryViewSet.as_view()),
    path('', include(router.urls))
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

应用程序结构:

- myproject/
 - cover_image/
 - media/
 - myproject_api/
  - models.py
  - serializers.py
  - ...
  - myproject/
   - settings.py
   - ...

还有,我的主要urls.py文件(myproject / urls.py)

from django.contrib import admin
from django.urls import path, include
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myproject_api.urls'))
]

我可以成功发出POST请求&amp;它显示正确的图像链接,但当我点击图像链接时,它会给出错误。

enter image description here

出了什么问题?

请帮忙!

1 个答案:

答案 0 :(得分:2)

问题是您在app / url中添加了静态媒体网址。将其移动到您的项目/网址

项目/ urls.py

from django.conf.urls import include, url
from django.conf import settings
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myproject_api.urls')),
    url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,})
]