编辑:我解决了这个问题并在下面给出了答案。
我试图使用 django-storages使用 SFTP访问我的“Hetzner”存储盒( https://www.hetzner.com/storage/storage-box),它应该保存媒体数据,即我网站的用户可以使用的图像文件动态上传。
settings.py
我的文件的相应部分如下所示:
DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage'
SFTP_STORAGE_HOST = 'username.your-storagebox.de'
SFTP_STORAGE_ROOT = '/media'
SFTP_STORAGE_PARAMS = {
'username': 'username',
'password': 'password',
'allow_agent': False,
'look_for_keys': False,
}
奇怪的是,当用户上传图片时,它被放置在存储空间中,我可以使用 SFTP 确认。但是从存储箱中获取图像失败,没有图像显示。控制台的摘录:
[03/Sep/2021 22:34:01] "GET /media/filename.jpg HTTP/1.1" 404 1962
我可以弄清楚 Django 仍在我的内部寻找MEDIA_DIR
文件。同样,我的设置的相应部分:
MEDIA_DIR = 'media'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_DIR)
MEDIA_URL = '/media/'
简而言之:使用 SFTP 似乎可以将文件放入存储中,但再次获取它们以某种方式失败。
我希望能得到一些帮助。提前致谢!
编辑:根据要求,我将提供更多代码片段
models.py
::
class SizeRestrictedImageField(ImageField):
def __init__(self, *args, **kwargs):
self.max_upload_size = kwargs.pop('max_upload_size', 0)
super().__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super().clean(*args, **kwargs)
file = data.file
try:
if file.size > self.max_upload_size:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s'
) % (filesizeformat(self.max_upload_size),
filesizeformat(file.size)))
except AttributeError:
logger.exception('An Exception occured while checking for max size of image upload. size: `%s`'
, file.size)
pass
return data
class ImageModel(models.Model):
image = SizeRestrictedImageField(upload_to=POST_PIC_FOLDER, null=True, blank=True,
help_text="Erlaubte Dateitypen: .jpeg, .jpg, .png, .gif", max_upload_size=MAX_IMAGE_SIZE)
我的urls.py
:
urlpatterns = [
path('defaultsite/', defaultsite_view, name='home'),
path('help', help_view, name="help"),
path('user/', include('user.urls')),
path('sowi/', include('sowi.urls')),
path('blog/', include('blog.urls')),
path('chat/', include('chat.urls')),
path('notifications/', include('notifications.urls')),
path('cookies/', include('cookie_consent.urls')),
path('', home_view, name="home"),
path('about/', AboutUsView.as_view(), name="about-us"),
path('impressum/', impressum_view, name="imprint"),
path('privacy/', privacy_view, name='privacy'),
path('privacy/statement/', privacy_statement_view, name='privacy-statement'),
path('agb', agb_view, name="agb")
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
我尝试+static(...)
从我的 url-patterns 中删除 -part,但这似乎并没有解决问题。