css Django没有在共享主机cPanel上加载媒体文件

xxls0lw8  于 4个月前  发布在  Go
关注(0)|答案(1)|浏览(60)

我有问题加载用户上传的媒体文件,并通过一个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管理媒体文件的服务,因为它负责将图像上传到media/images目录。
图像目录所在位置:/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)
3lxsmp7m

3lxsmp7m1#

将您的媒体根路径更改为public_html文件夹应该可以帮助您(在共享主机cPanel上)
before(您的项目目录中有媒体文件)

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

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

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

相关问题