从Django静态文件夹获取图像的正确方法

时间:2018-11-13 10:28:50

标签: python django

在我的setting.py中,我有下一个代码:

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static'),
]

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

在views.py中,我想按如下方式获取静态文件夹中的一些图像:

for f in ["static/img/logo/contact-form/logo_black.png", "static/img/logo/contact-form/logo_white.png":
    fp = open(os.path.join(BASE_DIR, f), 'rb')
    msg_img = MIMEImage(fp.read())
    fp.close()
    msg_img.add_header('Content-ID', '<{}>'.format(f))
    msg.attach(msg_img)

但是我遇到一个错误:

"[Errno 2] No such file or directory: '/Users/Admin/Projects/web-dealers/webDealers/static/img/logo/contact-form/logo-black.png'"

更新

urls.py如下:

urlpatterns = [
    url(r'^django-admin/', admin.site.urls),

    url(r'^admin/', include(wagtailadmin_urls)),
    url(r'^documents/', include(wagtaildocs_urls)),

    url(r'^search/$', search_views.search, name='search'),
    url(r'^api/', include('API.urls')),
    url(r'^contact-us/', contact_us, name="contact_us"),

    # Languages
    url(r'^i18n/', include('django.conf.urls.i18n'), name='set_language'),
    url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),

    # For anything not caught by a more specific rule above, hand over to
    # Wagtail's page serving mechanism. This should be the last pattern in
    # the list:
    url(r'', include(wagtail_urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

django中的静态信息总是很棘手,也很糟糕。我不知道为什么:)您没有DEBUG=False并忘记做python manage.py collectstatic吗?

但是,这对我有用:

settings.py

INSTALLED_APPS = [
    ...some other applications....

    'django.contrib.staticfiles',

    ...some other applications....

]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

urls.py中没有任何内容。我可以正常访问静态文件,例如: localhost:8000/static/image.png

编辑:

似乎我没有正确阅读并回答了不同的问题:)您的问题不在静态文件服务期间,而是在后端内部访问时。它说:找不到文件。您确定路径正确吗?还是os.path.join(BASE_DIR', 'static')确实包含文件?您尝试使用绝对路径访问文件,因此无论该文件是否存在,都必须易于验证:

'/Users/Admin/Projects/web-dealers/webDealers/static/img/logo/contact-form/logo-black.png'