代码之家  ›  专栏  ›  技术社区  ›  Boky

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

  •  0
  • Boky  · 技术社区  · 7 年前

    在my 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'"
    

    更新

    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 回复  |  直到 7 年前
        1
  •  0
  •   Radek Hofman    7 年前

    在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'