Problem:
I'm getting error:
"GET /soupiska/pic/hraci/download_6BVC8qn.jpeg HTTP/1.1" 404 2971
but "soupiska" is the APP folder.
Settings
Django 5.1.5
Settings.py includes:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import static
from django.conf import settings
urlpatterns = [
...
] + static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The path saved in the database is: pic/hraci/download_6BVC8qn.jpeg
The media folder is outside the APP, in the project folder (to have ability share media with other apps).
Cause
The reason for this behavior is, that I'm in APP URL:
Question
How to set up Django, to get the media from a folder in the project root, even I'm in the APP URL?
Additional info:
Render file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My Website</title>
<link rel="icon" href="./favicon.ico" type="image/x-icon" />
</head>
<body>
<main>
<h1>Soupiska</h1>
<table border="1">
{% for hrac in hraci %}
<tr>
<th>{{ hrac.cislo }}</th>
<th>{{ hrac.jmeno }}</th>
<th>{{ hrac.prijmeni }}</th>
<th>{{ hrac.post }}</th>
<th>{{ hrac.datum_narozeni.year }}</th>
<th>{{ hrac.fotka }}</th>
<th><img src="{{ hrac.fotka }}"" /></th>
</tr>
{% endfor %}
</table>
</main>
</body>
</html>
Picture physical location:
To use an Image
in a Template
, you need the absolute public path to the Image
which you can get via the url
[djangoproject.com] attribute of the Image
.
Change this line:
<th><img src="{{ hrac.fotka }}" /></th>
To:
<th><img src="{{ hrac.fotka.url }}" /></th>