Get the file path for a static file in django code

static files django
django static files not working
django static files not found in production
django static files 404
django serve static files in production
django static files tutorial
django media files
django can't find static files

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

Managing static files (e.g. images, JavaScript, CSS), django.contrib.staticfiles collects static files from each of your applications (and any other By default, collected files receive permissions from FILE_UPLOAD_PERMISSIONS and Then set the STATICFILES_STORAGE setting to 'path.to. Just like its parent, you can use it to write tests that involve running the code under� Go to the Static Files section; Enter the same URL as STATIC_URL in the url section (typically, /static/) Enter the path from STATIC_ROOT into the path section (the full path, including /home/username/etc) Then hit Reload and test your static file mapping by going to retrieve a known static file. Eg, if you have a file at /home/myusername

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' %}

The staticfiles app | Django documentation, set STATIC_ROOT in settings.py; run python2.7 manage.py collectstatic (or The important thing is this needs to be the full, absolute path to your static files folder. Finally, set up a static files mapping to get our web servers to serve out your� See the 3rd line. {% load static %} tag will inform Django that there are static files in this template. Django will then check for the related static files. Then sends them together with the HTML code. After that, we gave the src of the image tag. The source of image tag is a Django tag. Here we used static keyword and the path to the image.

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

How to setup static files in Django, In my getting started with Django tutorial, I showed you how to get a Django site up and running. Using the collectstatic command, Django looks for all static files in your gather all static files into a folder called staticfiles in our project root directory. Let's add the final code to serve up our templates. STATIC_URL = '/static/'. In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE. {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image">. Store your static files in a folder called static in your app. For example my_app/static/my_app/example.jpg. Serving the files.

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.

Working with Django Templates & Static Files ― Scotch.io, With Django static files tutorial, you will learn the concept of static files, project creation process and static files management in Django. files. There is a catch here. Then, the developer will have to change the code on every single page. from django.urls import path; from .views import *; urlpatterns =� A Django application, generally there are two types of static files. First, static files within the application, and second, Django comes. According to example, static files within the application code in the front and settings.py the same level static directory. STATICFILES_DIRS = (os.path.join(BASE_DIR, ' static '),)

Django Static Files Handling made Simple, Now if you run the following commands, you will get the result as shown. To serve the files uploaded by the user you will have to add the following line of code into your urls.py file. In Django, we refer to these files as “static files”. use the static template tag to build the URL for the given relative path� I set the static url to BASE_DIR and then I ended up with a bunch of extra folders in there that didn't make much sense. I don't understand how things have changed this much between 3.0 and 3. I legit used to be able to just do os.path.join(BASE_DIR, "path"), now I can't and it doesn't make sense as to why that is.

Managing Static Files in Django. By the Clueless Coder, In this lesson, we will learn how to use static files in Django. Create a new directory called static in the Django project root above, add the following code towards the end of the settings.py file: On the other hand, if there is a problem in loading files you would get 404 error in the console as follows:. This document describes Django’s file access APIs for files such as those uploaded by a user. The lower level APIs are general enough that you could use them for other purposes. If you want to handle “static files” (JS, CSS, etc.), see Managing static files (e.g. images, JavaScript, CSS).

Handling Static Content in Django, To get templates up and running, you will need to setup a directory in which We then take the absolute path to the settings file, extracting the path to the To implement this functionality, add the following code to the top of settings.py . Settings for managing static files. Static files include stuff like CSS, JavaScript and images that you may want to serve alongside your site. Django is very opinionated about how you should include your static files. In this article, I will show how to go about adding static files to a Django application.

Comments
  • Thanks. This should be the accepted answer, since OP asked for a filesystem path not a URL.
  • @SergeRogatch, in production, static files are served by apache/nginx, so this method won't work like debug model.
  • In a view, this returns a relative URI (e.g. to inject into html), not a filesystem path for use with open()