Django unable to load JS and CSS files as static resources

时间:2016-07-11 20:59:42

标签: python django

I have a html file called base.html inside a folder called html. There are two directories at the same level as html - js and css which contain static resources. The base.html refers those static resources through relative paths, like

<script type="text/javascript" src="../js/debounce.js"></script>
<link rel="stylesheet" href="../css/base.css">

It works as expected. Now I copied the entire directory structure to my django project. This is how the root folder ecom looks like:

enter image description here

The customviews directory contains the html, js and css directories, as well as a myview.py file, which is refered to in the urls.py file within the ecom subdirectory as:

from customviews.myview import *
urlpatterns = [url(r'^admin/', admin.site.urls),
               url(r'^time/$', current_datetime),
               url(r'^base/', base)]

The base method in myviews.py simply runs as follows:

def base(request):
    return render_to_response("base.html")

And the relevant part of settings.py looks like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'DIRS': [os.path.join(dirfunc(dirfunc(__file__)), 'templates').replace('\\', '/'),
                 os.path.join(dirfunc(dirfunc(__file__)), 'customviews/html').replace('\\', '/'),
                 os.path.join(dirfunc(dirfunc(__file__)), 'customviews/js').replace('\\', '/'),
                 os.path.join(dirfunc(dirfunc(__file__)), 'customviews/css').replace('\\', '/')],
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

When I fire up the server and load base, only the basic html is rendered, the css and js are missing. How do I load both?

1 个答案:

答案 0 :(得分:3)

You don't need to be including the static resource folders in your template dirs. What you do need to do is set your STATICFILES_DIRS under settings and include a static tag in your templates are calling those resources.