【问题标题】:Django is not loading media files on shared hosting cPanelDjango 没有在共享主机 cPanel 上加载媒体文件
【发布时间】:2022-06-13 02:21:09
【问题描述】:

我在加载用户上传的媒体文件并在 DEBUG = FALSE 时通过 template.html 文件显示它们时遇到问题。显示静态文件,但每当我加载页面时,我都会收到webaddress/media/images/image1.png 404 Not Found。我遵循了一些指南并将urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 添加到我的urls.py,但我仍然收到404 错误。我已经与 cPanel 托管服务提供商聊天,他们说我无权修改 cPanel Apache httpd.conf 文件,所以我希望 Django 管理媒体文件的服务,因为它处理将图像上传到 @ 987654324@目录。

图片目录所在位置:/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)

【问题讨论】:

    标签: html css django


    【解决方案1】:

    将您的媒体根路径更改为public_html 文件夹应该会对您有所帮助(在共享主机 cPanel 上)

    之前(您的项目目录中有媒体文件)

     MEDIA_ROOT = '/home/{username}/{project}/media' ✖️
    

    之后(现在它们存储在 public_html 文件夹中)

     MEDIA_ROOT = '/home/{username}/public_html/media' ✔️
    

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 2020-10-01
      • 2017-07-09
      • 2018-09-04
      • 2012-04-12
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多