[Django]-How to add my own files to django 'static' folder

5πŸ‘

βœ…

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.

1πŸ‘

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

πŸ‘€Daniel Rucci

1πŸ‘

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.

πŸ‘€alacy

-2πŸ‘

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,
        }))

Leave a comment