[英]Django DEBUG=False won't upload files to STATIC_ROOT
我試圖讓用戶能夠在我使用Django
創建的網站上上傳圖像,並且在使用DEBIG=True
運行時圖像上傳正常,但問題是當DEBUG=False
時圖像文件不會上傳到MEDIA_ROOT
而不是它被上傳到STATIC_DIRS
。 此外,即使在執行python manage.py collectstatic
后已經在MEDIA_ROOT
中的文件也不會加載到模板中,圖像 URL 會出現404 Page Not Found
錯誤。
CSS 和 JS 文件仍在提供,因此這意味着只有媒體 url 不工作。
以下是我正在使用的代碼。
網址.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Home.urls')),
path('account/', include('Account.urls')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
設置.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
請注意,我使用whitenoise
作為存儲后端。
這是用於上傳文件的 model 代碼。
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(self.path, filename)
rename_pp = PathAndRename('img/profile-pictures')
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
avatar = models.ImageField(upload_to=rename_pp, blank=True, null=True, default='img/profile-pictures/default-profile-pic.png')
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
image = Image.open(self.avatar.path)
if image.width > 100 or image.height > 100:
output_size = (100, 100)
image.thumbnail(output_size, Image.ANTIALIAS)
image.save(self.avatar.path, file_quality=100)
使用DEBUG=True
時,這意味着您處於開發端,因此您的本地計算機能夠提供文件(媒體文件),但使用DEBUG=False
時,它就像您現在處於部署端一樣。
要從中提供媒體文件,您需要有一個存儲桶(如 amazon S3)來存儲這些文件並從那里獲得服務。
因此,如果您的媒體文件在DEBUG=True
時工作正常,那就意味着它很好。
現在您只需要一個存放它們的地方。
我用這個代替你的 STATICFILES_STORAGE 並且當 debug=False 一切正常。
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.