解决Django collectstatic报错:找不到storages.custom_azure.AzureStaticStorage后端
解决Django中Azure存储后端找不到的问题
错误原因
报错Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure'的核心原因是存储类路径配置不匹配:你将AzureStaticStorage类定义在uploader应用的custom_azure.py文件中,但在settings.py里错误指定了storages.custom_azure.AzureStaticStorage,Django会尝试去storages模块下查找不存在的custom_azure文件,导致报错。
修复步骤
1. 修正settings.py中的存储后端路径
将STATICFILES_STORAGE的路径改为指向uploader应用下的custom_azure模块,与DEFAULT_FILE_STORAGE保持一致:
# settings.py DEFAULT_FILE_STORAGE = 'uploader.custom_azure.AzureMediaStorage' # 修正这一行的路径 STATICFILES_STORAGE = 'uploader.custom_azure.AzureStaticStorage'
2. 修复custom_azure.py中的语法错误
AzureMediaStorage类里的account_name赋值存在语法错误(多了一个单引号),修正为:
# uploader/custom_azure.py from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = 'name' # 移除多余的单引号 account_key= 'key' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'name' account_key = 'key' azure_container = 'static' expiration_secs = None
3. 重新执行collectstatic命令
确保激活pipenv虚拟环境后,运行:
pipenv run python manage.py collectstatic
额外优化建议
- 避免将Azure账户密钥硬编码在代码中,建议通过环境变量获取,例如
os.getenv('AZURE_ACCOUNT_KEY'),防止密钥泄露。 - 确认
uploader应用已正确添加到INSTALLED_APPS(当前配置已满足,无需修改)。
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

