Get the file path for a static file in django code - python

I have a django application that sends off an email containing image files as MIME attachments. The emails are sent from views.py, but in order to attach the files, I need to get the full path name of the image(s), so python can open them. These files are in the static folder in my app, but I can't seem to find a way that I can get the full path of the file on the filesystem that works in development mode - It works fine in production after collecting static, but in dev, it can't find the file as the static files are served from individual app folders in development.

Use finders-module of Django
from django.contrib.staticfiles import finders
result = finders.find('css/base.css')
searched_locations = finders.searched_locations
String result is the file-system path, and if not found, double check searched_locations

project_dir.url add to the end of file
if DEBUG:
urlpatterns += patterns(
'',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': STATIC_ROOT}),
)
project_dir.settings
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static_debug')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
make dirs media & static_debug (add them to .gitignore)
project_dir/
static/
image.jpg
settings.py
urls.py
apps/
__init__.py
some_app/
static/
some_app/
css/
style.css
media/
static_debug/
Now you can run project or directly
python manage.py collectstatic
access from views
from django.templatetags.static import static
static('image.jpg')
static('some_app/css/style.css')
access from templates
{% load staticfiles %}
{% static 'image.jpg' %}
{% static 'some_app/css/style.css' %}

After doing lots of mistakes the following thing worked for me..
Suppose you have following directory structure (Thanks #madzohan)
project_dir/
static/
image.jpg
settings.py
urls.py
apps/
__init__.py
some_app/
static/
some_app/
css/
style.css
And now if you want to get the path of project_dir/static/image.py then
In your project_dir/settings.py file define a STATIC_DIR varaible on the file scope like. ( If not done before )
project_dir/settings.py
import os
# after your other file variables
STATIC_DIR = os.path.join(BASE_DIR, 'static')
Now in your app_name/views.py file from where you want to acess the /static/image.jpg file
app_name/views.py
import os
from project_dir.settings import STATIC_DIR
# here I want the /static/image.jpg file then
image = os.path.join(STATIC_DIR, 'image.jpg')
And then you can have acces to image.jpg file throught image variable
Hope this works well for you

Since you want an app's static, here's what you need!
from django.contrib.staticfiles import finders
APP_LABEL = 'app_youre_looking_at'
FILE_NAME = 'file_name_you_want_to_read_or_write.ext'
stores = finders.AppDirectoriesFinder(app_names={APP_LABEL}).storages
print(f'Here it is: {stores[APP_LABEL].path(FILE_NAME)}')
The FILE_NAME is not required to exist. You can use stores[APP_LABEL].path('') to get path only.

Related

Django Static Files - CSS File Won't Load

I am learning Django, and am trying to load a static css file.
I have seen the other questions and read the docs, but I am still unable to see the problem.
I am using Django 1.11.
Here is my urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My settings.py (only the part to do with static files):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
STATICFILES_DIRS = (
STATIC_ROOT,
)
And the part of my template where I try and load the files:
{% load static %}
Whenever I load the index.html template, the following error messages are displayed by my console:
core.js:5 Uncaught ReferenceError: define is not defined
at core.js:5
localhost/:12 GET http://localhost:8000/static/css/homepage.css
localhost/:11 GET http://localhost:8000/static/css/horz-navbar.css
localhost/:10 GET http://localhost:8000/static/css/fonts.css
localhost/:13 GET http://localhost:8000/static/css/style.css
Here is the file directory structure:
mysite
db.sqlite3
manage.py
mysite
__init__.py
settings.py
urls.py
views.py
wsgi.py
static
admin
css
fonts.css
horz-navbar.css
homepage.css
style.css
templates
index.html
So Django doesn't seem to recognize that the files exist, I have checked and made sure that the files exist on my computer, and I'm not sure if this was needed, but I have also run python manage.py collectstatic
Please tell me if you need anymore information.
Change your STATIC_ROOT into another name and then update your STATICFILES_DIR. Something like this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Replace "{% static "css/fonts.css" %}" with "{% static 'css/fonts.css' %}". There's a mismatch between quotations.

How to add my own files to django 'static' folder

I've read django static files document and made my django static files settings like this
setting.py
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
html page
<img src="{% static "admin/img/author.jpg" %}" alt="My image"/>
So if I address one of django default static files, it works fine. But if I add my own file and folders to the static folder, it doesn't show it.
I tried
python manage.py collectstatic
But nothing changed. How can I make it work?
A few things...
STATICFILES_DIRS = (
'path/to/files/in/development',
)
STATIC_ROOT = 'path/where/static/files/are/collected/in/production'
When DEBUG = True, Django will automatically serve files located in any directories within STATICFILES_DIRS when you use the {% static 'path/to/file' %} template tag.
When DEBUG = False, Django will not serve any files automatically, and you are expected to serve those files using Apache, Nginx, etc, from the location specified in STATIC_ROOT.
When you run $ manage.py collectstatic, Django will copy any and all files located in STATICFILES_DIRS and also files within any directory named 'static' in 3rd party apps, into the location specified by STATIC_ROOT.
I typically structure my project root as such:
my_project/
/static_assets/ (specified in STATICFILES_DIRS)
/js
/images
/static (specified in STATIC_ROOT)
I hope that helps you understand how the staticfiles app works.
STATIC_ROOT is where files are collected and moved to when collectstatic runs.
If you want files to be consolidated to there they should be found by the static file finder.
As an example, include the following in your settings
STATICFILES_FINDERS = ("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
now for one of the apps that are a part of your project, create a folder called static and put something in it.
When you run collectstatic you should see that file mentioned and it copied to your STATIC_ROOT
You can try adding
STATICFILES_DIRS = (
STATIC_PATH,
)
to your settings.py.
Also, if you haven't already, make sure to include
{% load static from staticfiles %}
in each of your templates where you wish to reference static files.
Lastly, make sure that the file you are referencing actually exists and the file path to it is correct.
Try to:
<img src="{{ STATIC_URL }}admin/img/author.jpg" alt="My image"/>
And in your view must be something like this:
...
from django.shortcuts import render_to_response
from django.conf import settings
def my_view(request):
...
static_url = getattr(settings, 'STATIC_URL')
...
return render_to_response(
template_name,
RequestContext(request, {
'STATIC_URL': static_url,
}))

STATIC_URL issue in django 1.5.4

I wanted to enable serving static files through django 1.5 builtin development server. I came across a strange problem.
If I make a request to my static file using localhost:8000/static/staticstyle.css then it responds me with 404 not found. But If I make a request to the same file without the value mentioned in the STATIC_URL and add the url pattern as "url(r'^anyval_other_than_mentioned_STATIC_URL/', django.views.static.serve,{'document_setting':settings.STATIC_ROOT}), ", then it responds me with 304 , which is conditional get.
I have collected all the static files in the static directory setup in the settings file and enabled all the context processor required for the template.
For production I have used nginx to serve the static file so there is no problem.
My settings.py looks like
STATIC_ROOT = APPLICATION_PATH+"/static/"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('vendors',APPLICATION_PATH+'/vendors'),
('admin/assets/',APPLICATION_PATH+'/templates/admin/assets'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
My application urls.py looks like
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Any hints would be highly appreciated.
Thank you .
please read this first
https://docs.djangoproject.com/en/1.5/howto/static-files/
There are some settings related to static files serve
The list of finder backends that know how to find static files in various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Absolute path to the directory static files should be collected to
STATIC_ROOT = os.path.join(APPLICATION_PATH, '..', 'static')
URL prefix for static files.
STATIC_URL = '/static/'
You can specify Additional locations of static files
STATICFILES_DIRS = (
os.path.join(APPLICATION_PATH, 'vendors'),
os.path.join(APPLICATION_PATH, '/templates/admin/assets'),
)
There is special application for static serve in django contrib
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
...
)
After You have configured your project run collectstatic command
python manage.py collectstatic
This will copy all files from your static folders into the STATIC_ROOT directory.

Django 1.4 serving media files works, but not static

I am using Django 1.4 and for some reason i am able to serve media files, but not the static ones...
Here is my code:
settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
base.html:
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ MEDIA_URL }}css/bootstrap-colorpicker.css" rel="stylesheet">
i get a 404 http not found... what am i doing wrong? An i did create the static folder in my project right next to media
http://mysite.com:8000/static/css/bootstrap.css
Your static folder should be under one app that you use it for.
For example, I have a project named my_project and an application named my_app, I have some static files used in my_app so I put them under ~/project_path/my_project/my_app/static
NB: my_app must be in INSTALLED_APPS. See STATICFILES_FINDERS documentation.
Edit:
As a best practice, you should have a global static folder in one app (the main one), for example a static folder how contains your html template basic resources as jquery, bootstrap, your global style.
And for the static files how's required only for one app, for example app foo, these files should be under foo/static folder
I suggest removing the explicit media and static views and allowing the staticfiles app to create them (when DEBUG is True under development).
Check the default finders are present in your settings.py
https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
Either add your project static directory to STATICFILES_DIRS (https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS) or place app specific static folders under each app. The app needs to be listed in the INSTALLED_APPS for the finders to locate the static content.
Do not place static files into STATIC_ROOT yourself. This directory is managed by the collectstatic command. See https://docs.djangoproject.com/en/dev/howto/static-files/#deployment
Here is how i define my media url in settings.py:
import os
ABSOLUTE_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(ABSOLUTE_PATH, '../media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(ABSOLUTE_PATH, '../static')
STATIC_URL = "/static/"
So like you see the difference is ../media and ../static
Is mysite in your installed apps ? Django look inside your installed apps and check if there's a static folder there.

How to work properly with django static files

i have a problem with django static files handling.
I am confused about how to use MEDIA_ROOT, STATIC_ROOT, MEDIA_URL and STATIC_URL
I have a file structure like this(sorry, i dont know how to indent properly :S):
static/
css/
img/
js/
For example, if I have a .css file in my css dir, how could I reach it?
MEDIA_ROOT and MEDIA_URL are deprecated. Use STATIC_ROOT and STATIC_URL.
STATIC_ROOT = "Absolute path to your static directory" (Example: /home/your_app/static)
STATIC_URL = "/static/" (Could be anything you would like to use)
When you want to serve static content pass the context_instance and in your template use,
{{STATIC_URL}}/file_path_from_static_directory/
EDIT:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Categories