I'm trying to write some code that checks if a static file exists while in DEBUG mode, and I can't get it working. Here's what I've tried in the console:
>> from django.conf import settings
>>> settings.DEBUG
True
>>> from django.contrib.staticfiles.storage import staticfiles_storage
>>> staticfiles_storage.exists('img/vi_crumbs_bkg.gif')
False
This fails, despite vi_crumbs_bkg.gif
existing in my app's static directory. If I symlink it to settings.STATIC_ROOT
, it all works as expected.
So, is there any way I can get staticfiles_storage.exists
to work while in DEBUG mode?
(note: while I know I could just run collectstatic to get this properly working, I'd hate to periodically run that to collect all the assets from all my apps while I'm actively developing)
Thanks in advance -
Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.
collectstatic. Collects the static files into STATIC_ROOT . Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you're confused, the findstatic command can help show you which files are found.
STATIC_URL is simply the prefix or url that is prepended to your static files and is used by the static method in Django templates mostly. For more info, read this. STATIC_ROOT is the directory or location where your static files are deployed when you run collectstatic .
The STATIC_ROOT variable in settings.py defines the single folder you want to collect all your static files into. Typically, this would be a top-level folder inside your project, eg: STATIC_ROOT = "/home/myusername/myproject/static" # or, eg, STATIC_ROOT = os. path.
I think I've got a solution. Instead of using staticfiles_storage.exists
, I'm going to rely on Django's staticfile finders to find the file for me. Like so:
>>> from django.contrib.staticfiles import finders
>>> finders.find('img/vi_crumbs_bkg.gif')
u'/home/myuser/django_project/app_root/static/img/vi_crumbs_bkg.gif'
This should be perfect for my needs, since all I need to do is check that a file exists in one directory and not another - regardless of it being in the app's root or the STATIC_ROOT
is irrelevant.
Hope this helps someone else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With