Proper way to get images from Django static folder - python

In my setting.py I have next code:
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/'
And in views.py I want to get some of the images inside static folder as follows:
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)
But I'm getting an error:
"[Errno 2] No such file or directory: '/Users/Admin/Projects/web-dealers/webDealers/static/img/logo/contact-form/logo-black.png'"
UPDATE
The urls.py is as follows:
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)
What am I doing wrong?

Static in django are always tricky and a hell. I do not know why:) Don't you have DEBUG=False and forgot to do python manage.py collectstatic?
However, this works for me:
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',
)
I do not have anything in urls.py. I can access static files normally like: e.g. localhost:8000/static/image.png.
EDIT:
It seems that I did not read that properly and answered something different:) Your problem is not during the static files serving but when you access internally at the backend. It says: file not found. Are you sure that the path is correct? Or, that the os.path.join(BASE_DIR', 'static') really contains the file? You try to access the file using and absolut path so it must be easily verifiable is it is there or not at:
'/Users/Admin/Projects/web-dealers/webDealers/static/img/logo/contact-form/logo-black.png'

Related

Why 404 error occurs even though I have set STATIC_ROOT and urls.py

I don't know why, but I get 404 errors when trying to use static file like this: {% static 'js/some.js' %}.
Here's my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path("account/", include("account.urls")),
path("", include("post.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And this is my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static/'
# media config
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / 'media/'
Thanks!!
EDIT
Here's the error I get
GET http://127.0.0.1:8000/static/js/some.js net::ERR_ABORTED 404 (Not Found)
And the url you can see here is right.
Please try this:
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]

Can not create media folder in Django Project

Media folder is not getting created when I run the server. I am working in localhost.
You can see the urls.py and settings.py code below.
I added 'django.template.context_processors.media' to the templates. My Django Version is 2.0.3 and I am using Python 3.6.8.
When I run the code, media folder should be created automatically. How can I fix that issue?
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #settings.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = "index"),
path('about/', views.about, name = "about"),
path('articles/', include("article.urls")),
path('user/', include("user.urls")),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #urls.py
For a media file to be created,you need to add a slash after 'media' in the MEDIA_ROOT
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
instead of:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Django static files urls setting

Please help me check my static setting
when Debug =False,it works well
But when Debug=True,It can't catch the static files
Please help me, Thank you.
Here is my settings.py:
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
urls.py
from django.conf import settings
urlpatterns = patterns('',
url(r'', include('core.urls', namespace='core')),
)
if settings.DEBUG is False:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
else:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
If you will write the below code in urls.py it will work for both the DEBUG status
url( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ),
and one thing to be noted my static root is like for django 1.4+
PROJECT_DIR = os.path.dirname(os.path.dirname( __file__ ))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
along with this you need to do the following command to copy all static files to PROJECT_PATH/static dir
python manage.py collectstatic

Static Files With Django Development Server 1.7 Slightly Different Directory Settings

This is my website directory:
django_project
\bin
\include
\lib
\src
\django_project
settings.py
\app2
manage.py
\static
\js
\css
\media
\templates
base.html
What I have added to my settings.py is:
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "templates"),
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static"),
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media"),
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static"),
),
and to my urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and hey, it does'nt work. The way I refer to them in the base.html is:
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
Any ideas?
Thank you.
Hasan
Running the settings that you've pasted gave me an error ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. Commenting-out os.path.join(os.path.dirname(BASE_DIR), "static"), in the settings removed the error and the template correctly found the CSS file without the URLs.py modifications.
First of all as #r---------k mentioned, I should not have had trailing commas except for the tuples. So the settings.py should look like:
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static")
),
And the second thing is that, as you may notice, STATIC_ROOT and STATICFILES_DIRS cannot possibly have the same value. I added another static folder inside the static folder and put my js and css folders inside of it:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static")
),
The directory looks like:
django_project
\bin
\include
\lib
\src
\django_project
settings.py
\app2
manage.py
\static
\static
\js
\css
\media
\templates
base.html
Finally, you should have the urlpatterns in your urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This seems to work in current django (2.2) in your urls.py:
from django.conf import settings
from django.conf.urls.static import serve
from django.urls import include, path
urlpatterns += [
path(settings.STATIC_URL[1:], serve, {'document_root': settings.STATIC_ROOT })
]
Remember to run ./manage.py collectstatic to collect the static files to settings.STATIC_ROOT

Django debug-toolbar - Can't make it work (ImproperlyConfigured: The STATICFILES_DIRS ...)

The error (when running the django runserver command):
ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
I don't really use django static (this is mostly and api server) and I just want django debug to debug and explain my sql queries. So what I have is:
STATIC_DIRECTORY = '/'
MEDIA_DIRECTORY = '/media/'
STATIC_URL = S3_URL + STATIC_DIRECTORY
MEDIA_URL = S3_URL + MEDIA_DIRECTORY
STATICFILES_STORAGE = 'server.s3utils.StaticRootS3BotoStorage'
DEFAULT_FILE_STORAGE = 'server.s3utils.MediaRootS3BotoStorage'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
abs_path('staticfiles'),
# ABS_PATH('/static/'), #D either
)oesn't work either
)
EDIT: If I just remove STATICFILES_DIRS the errors changes:
TypeError at /admin/ Error when calling the metaclass bases
function() argument 1 must be code, not str Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.6.2
Exception Type: TypeError Exception Value: Error when calling the
metaclass bases
function() argument 1 must be code, not str
I also tried as one of the answers suggested to add
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
Doesn't help..
I guess that I'm missing something very simple (but annoying) I'll be glad for help with this.
Django debug toolbar chokes when using S3BotoStorage. I mostly wanted SQL logging, so adding this code to settings.py to disable the StaticFilesPanel was a workaround for me:
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
# 'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
This django-debug-toolbar explicit-setup
Says something about:
from django.conf import settings
from django.conf.urls import include, patterns, url
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
Have you tried?
I had encountered the same error when I created custom storage using lambda:
StaticRootS3BotoStorage = lambda: S3Boto3Storage(bucket_name='example-name')
Changing it to class solved the problem:
class StaticRootS3BotoStorage(S3Boto3Storage):
bucket_name='example-name'
pip install django-debug-toolbar
check your settings.py file :
INSTALLED_APPS = [
'django.contrib.staticfiles',
'debug_toolbar',
...
MIDDLEWARE = [
"debug_toolbar.middleware.DebugToolbarMiddleware",
...
]
...
INTERNAL_IPS = [
"127.0.0.1",
]
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
urls.py
path("__debug__/", include(debug_toolbar.urls)),
And run this command : python manage.py collectstatic

Categories