Struggling with loading user-uploaded media files and displaying them through a template.html file when DEBUG is set to FALSE. The static files are showing up fine, but every time I try to access the page, I keep encountering a 404 error for
webaddress/media/images/image1.png
. Even after following some suggested steps like adding urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to my urls.py
, the issue persists. Unfortunately, the cPanel hosting provider informed me that I can't modify the Apache httpd.conf file on cPanel, so now I'm exploring options to let Django handle the serving of these media files since it's responsible for image uploads to the media/images
directory.
Location of the images directory:
/home/<cPanelUserName>/repositories/djangoApp/media/images
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
template/index.html
<body style="background: url('{{ background_pic.url }}'); background-size: cover; background-position: center; background-attachment: fixed;">
<div id="profile">
<img id="userPhoto" src="{{ profile_pic.url }}" alt="{{ profile_pic_title }}">
</div>
</body>
models.py
class profilePic(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
class backgroundPic(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
views.py
def index(request):
imageModel = profilePic.objects.get(pk=1)
backgroundModel = backgroundPic.objects.get(pk=1)
return render(
request,
"template/index.html",
{
"profile_pic_title":imageModel.title,
"profile_pic":imageModel.image,
"background_pic_title":backgroundModel.title,
"background_pic":backgroundModel.image,
}
)
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('', include('SocialLinks.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)