Alan Tingey Alan Tingey - 1 month ago 12
Python Question

Django: Static Files not displayed on deployment server

I can not get my site to load the static files correctly.

settings.py files in regards static files is as follows:

# Static files
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/str8red.com/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)


When I run the following command:

python manage.py collectstatic


I get the following outcome:

1858 static files copied to '/var/www/str8red.com/static'


When I check the directory everything seems to have worked correctly.

I then go and checkout my site online at "https://str8red.com/" and none of the css or images are working. An example error I am seeing in chrome developer mode is as follows:

GET https://str8red.com/static/str8RED.png 404 (Not Found)


The file is being grabbed using the following code:

{% load staticfiles %}
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'index' %}">
<img src="{% static 'str8RED.png' %}" width="97" height="22" alt="str8RED.com" />
</a>


URL file:

from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from dwad import settings

urlpatterns = [
url(r'', include('meta.urls')),
url(r'^straightred/', include('straightred.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^chaining/', include('smart_selects.urls')),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^accounts/', include('allauth.urls')),
]

# Get Django to serve media files in debug mode.
if settings.DEBUG:
urlpatterns += [url(r'^resources/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})]


Any help greatly appreciated, many thanks, Alan.

Answer

You need to add static url rule in your urls.py in order to tell Django to serve static files when any static url is fetched.

if not settings.DEBUG:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.STATIC_ROOT}),
    ]