0

I configured the media directory, but I can not access the image under the media directory:

Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/images/datadictionary/zfb.png

This is the setting in my settings.py:

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

My directories in project, you see there is a zfb.png there:

My DataDictionary model is bellow:

class DataDictionary(models.Model):
    appmodelfield = models.CharField(max_length=64, null=True)  # app_model_field
    name = models.CharField(max_length=16, help_text="总的名称")
    content = models.CharField(max_length=32, help_text="内容")
    image = models.ImageField(upload_to="images/datadictionary/", null=True, help_text="图标")
    parentlevel = models.CharField(max_length=16, null=True, help_text="父级")

You can see my ImageField, and I also pip installed the pillow.

And the django rest framework web browser response data is:

[
    {
        "id": 5,
        "appmodelfield": null,
        "name": "支付类型",
        "content": "支付宝",
        "image": "http://127.0.0.1:8000/media/images/datadictionary/zfb.png",
        "parentlevel": null
    }
]

You see the image field, it is indeed the directory image you see upper.

But I can not get the image in my browser.

Clément Denoix
  • 1,504
  • 11
  • 18
maer
  • 156
  • 3
  • 15

1 Answers1

1

Add this to your Project url.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is for Development environment only,when the DEBUG=False in your settings.py(in production environment),Django no longer handle static file and media file anymore,static file and media file will be handle by web server like apache etc.

Ykh
  • 7,567
  • 1
  • 22
  • 31