1

im relatively new to Django. I have an app where I specify MEDIA_URL and MEDIA_ROOT in settings.py file in project root. My pared down project structure looks like this:

/
../files
../files/media
../files/media/logo.png
../solid/settings.py
../solid/urls.py
/web/templates (contains all my HTML)

inside settings I have

MEDIA_ROOT   = BASE_DIR / 'files'
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = BASE_DIR  /'files'

in my template web/template/index.html I'm trying to reference it

<img src="{{% MEDIA_ROOT %}}/images/ourlogo.png" class="" alt="Logo" height="40">

In solid/urls.py I have:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',web_views.index,name="index"),
    ######################################################
    path('login/',login_page,name="login"),
    path('logout/',log_out,name="logot"),
    path('register/',register,name="register"),
    #######################################################
    path('upload/',web_views.upload,name="upload"),
    path('list/',web_views.list_uploads,name="list"),
    path('details/<int:oid>', web_views.view_download,name='view_download'),
    path('download/<str:filename>', web_views.download_file,name='download_file'),
    #######################################################
    path('paypal/', include("paypal.standard.ipn.urls")),
    path('payment/',web_views.upgrade,name="payment"),
    path('paypal-cancel/', PaypalCancelView.as_view(), name='paypal-cancel'),
    path('paypal-return/', PaypalReturnView.as_view(), name='paypal-return'),
    #######################################################
]+static('s/',document_root=settings.MEDIA_ROOT)

the image is not rendering.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
  • So _static_ **or** _media_? https://stackoverflow.com/questions/66833381/static-media-images-are-not-displaying-in-django/66834540#66834540 – Ivan Starostin Jun 06 '22 at 17:02
  • The first argument of [static](https://docs.djangoproject.com/en/4.0/ref/urls/#static) function must be settings.MEDIA_URL in your case. Just what is written in the docs example. Not `s/` which does not match your settings.py – Ivan Starostin Jun 06 '22 at 17:10

1 Answers1

1

settings.py

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

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

project_name/urls.py add this two lines with urlspatterns

urlpatterns = [
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

if want to get the image from database

 <img src="{{ img.photo_2.url }}" alt="" class="img-fluid">

here "img" is the dictionary key name. photo_2 is the database field name. and to show the image you have put the .url after that.

static image

  <link href="{% static 'img/favicon.png' %}" rel="icon">
Shojib Hasan
  • 176
  • 1
  • 7