Django static file 404 errors when deployed with mod_wsgi - css

I am getting 404 errors on all of my static files when I try to deploy them in production
A live page of the site is available here. Inspecting the page in Chromes Console or Firebug will show the below issues.
I cant understand why this is happening as the above 404 errors match perfectly to the locations of my CSS files
/var/www/bias_experiment/static/survey/css/bootstrap.css
I've tried to solve this for a few days but cant crack the problem.
Below is all of my setup. I thought it best to include everything that might be useful and all the steps I have taken. Apologies for the length.
settings.py
DEBUG = True
STATIC_ROOT = '/var/www/bias_experiment/static/'
STATIC_URL = '/bias_experiment/static/'
STATICFILES_DIRS = (
'/var/www/bias_experiment/src/survey/static/survey/css',
'/var/www/bias_experiment/src/survey/static/survey/js',
'/var/www/bias_experiment/src/survey/static/survey/fonts',
)
I am using STATIC_URL = '/bias_experiment/static/' because I am using a VM which has been made publicly available through http://phaedrus.scss.tcd.ie/bias_experiment/
If I use STATIC_URL = '/static/' I get 403 forbidden errors.
slide_test.html
{% load staticfiles %}
<!-- THESE WORK LOCALY BUT DO NOT WORK ON THE SERVER -->
<link rel = "stylesheet" href ="{% static "survey/css/bootstrap.min.css" %}" >
<link rel = "stylesheet" href ="{% static "survey/css/bootstrap.css" %}">
<link rel="stylesheet" href ="{% static "survey/css/jquery-ui.css" %}">
<link rel="stylesheet" href ="{% static "survey/css/slider.css" %}">
<script src="{% static "survey/js/jquery.min.js" %}"></script>
<script src="{% static "survey/js/jquery-ui.js" %}"></script>
<script src="{% static "survey/js/slider.js" %}"></script>
My default apache file /etc/apache2/sites-available/default
Alias /static/ /var/www/bias_experiment/static/
<Directory /var/www/bias_experiment/static>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias /bias_experiment /var/www/bias_experiment/src/bias_experiment/index.wsgi
<Directory /var/www/bias_experiment/src/bias_experiment>
<Files index.wsgi>
Order deny,allow
Allow from all
</Files>
</Directory>
...
standard apache default settings here
...
</VirtualHost>
As per the DjangoProject 1.6 Documentation (I am using Apache/2.2.22 (Ubuntu))
If you are using a version of Apache older than 2.4, replace Require
all granted with Allow from all and also add the line Order deny,allow
above it.
I have restarted and reloaded Apache
sudo service apache2 restart sudo service apache2 reload
I have no problem running collectstatic
I have set ownership of the collected files to www-data:www-data with the below command
sudo chown -R www-data:www-data /var/www/bias_experiment/static/
I have even disabled and re-enabled the default file in apache2
sudo a2dissite default
sudo a2ensite default
and then restarted
sudo service apache2 restart sudo service apache2 reload
I am using
Ubuntu 12.04
Apache 2.22
Django 1.6
mod_wsgi Version: 3.3-4ubuntu0.1
An absolute path to one of the CSS files is http://phaedrus.scss.tcd.ie/bias_experiment/static/survey/css/bootstrap.min in case it is of any use.
However I cant seem to get the test deployment page I am working to show its CSS or JS.
I really am not sure what I'm leaving out. If anyone can make any suggestions it would be hugely appreciated.
I asked a similar question to this a few days ago which i have deleted as there were too many mistakes on my part and it lacked both detail and a clear issue.
Thanks

For:
STATIC_URL = '/bias_experiment/static/'
in the Django settings module, you should be using:
Alias /bias_experiment/static/ /var/www/bias_experiment/static/
in the Apache configuration.

Don't use STATIC_ROOT in STATICFILES_DIRS. They shouldn't be the same. Because when you run python manage.py collectstatic for deployment they will be overwritten and also take a look at this page Managing static files (CSS, images)
#settings.py
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Introduce templates
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'somewhereelse'),
os.path.join(BASE_DIR, 'templates')]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'dajaxice.finders.DajaxiceFinder',
)
And this code for WSGI works for me
import os
import sys
import pprint
os.environ['DJANGO_SETTINGS_MODULE'] = 'Yourapp.settings'
import django.core.handlers.wsgi
class LoggingMiddleware:
def __init__(self, application):
self.__application = application
def __call__(self, environ, start_response):
errors = environ['wsgi.errors']
pprint.pprint(('REQUEST', environ), stream=errors)
def _start_response(status, headers, *args):
pprint.pprint(('RESPONSE', status, headers), stream=errors)
return start_response(status, headers, *args)
return self.__application(environ, _start_response)
application = LoggingMiddleware(django.core.handlers.wsgi.WSGIHandler())
path = '/var/www/example.com'
if path not in sys.path:
sys.path.append(path)

Related

static-files 404 not found on hosted django app

im having a hard time to display my static files on my webpages, im hosting my website on digitalocean ubuntu 18 and my static files are stored on the digitalocean space. initially everything was okay and working correctly until i added 3 new images to the server and ran the collectstatic command afterwards, note this was for the second time cause i ran it the first time to store the files in the digitalocean space folder i created. The collectstatic command shown me a warning saying
UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change "
after i continue by typing yes, the files are images are successfully stored in the digital-space, but ever since i ran the collect command for the second time all staticfile are not displayed. I did some further reading about this warning and used the solution from AWS S3 and Django returns "An error occurred (AccessDenied) when calling the PutObject operation" but still nothing changed the warning went away but the staticfiles are still not found.
heres the error message from the chrome browser: Failed to load resource: the server responded with a status of 404 (Not Found)
have you ensured your settings display this:
STATIC_ROOT = os.path.join('static')
STATIC_URL = '/static/'
Following this, your templates should show the following:
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/bootstrap.css' %}">
The best way to go about things in my opinion is to only collecstatic locally and then push all of the local files and directories up to the server. What do you currently use to transfer files to the server side?
The other thing you need to do is ensure that Nginx has the location of your static files set within the sites-available file. From your ssh terminal (server side terminal) you can type:
sudo nano /etc/nginx/sites-available/projectname
Within this you need to add the location of your statics, for example:
server {
ocation /static/ {
root /home/name/projectname;
}
}
The following documents are extremely useful:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04
I was using nginx server in digitalocean for my django project.
front-end static files were working but admin not.
See my static files setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
front-end css in static folder and collectstatic target folder is staticfiles
So our main focus is STATIC_ROOT means staticfiles folder. In nginx settings put "staticfiles" instead of "static" to set static file location.
Your STATIC_ROOT folder name could be anything you need to use that same name in nginx.
See below code for nginx setting:
location /staticfiles/ {
root /home/[your_username]/[your_project_folder];
}
[your_username]: which you are using to host your project on digitalocean.
The whole thing is that, you need to use your STATIC_ROOT folder in nginx setting.
Command to create/edit nginx setting is:
sudo nano /etc/nginx/sites-available/[your_project_folder]

Django static files - error 404 on access attempt

I'm following the gettingstartedwithdjango.com tutorials but with newer versions of code. I'm on the second tutorial and I'm near the end but I'm unable to successfully style my site with CSS due to 404 errors serving static files content. I'm not exactly clear on why.
I'm running a Vagrant VM atop Windows 7 for development, /vagrant (in the VM) is mapped to C:/VAGRANT (in Win7). I created C:/VAGRANT/PROJECTS to contain all of my projects. I created a virtualenv for my project which sits in /home/vagrant/blog-venv (in the VM), the contents for that project from a code perspective sit in C:/VAGRANT/PROJECTS/microblog.
DIRECTORY STRUCTURE
PROJECTS
static # subdirs not auto-created yet as functionality not yet working
uploads # subdirs not auto-created yet as functionality not yet working
microblog
manage.py <file>
assets
css
fonts
js
microblog
settings
templates
_layouts
blog
migrations
templates
blog
Based on the above directory structure, here are the relevant files and their contents:
/microblog/microblog/settings/__init__.py
from .base import *
try:
from .local import *
except ImportError:
pass
/microblog/microblog/settings/base.py
DEBUG = False
here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x)
TEMPLATES = [
{
'DIRS': [
root("templates")
},
]
MEDIA_ROOT = root("..", "..", "uploads")
MEDIA_URL = ''
STATIC_ROOT = root("..", "..", "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
root("..", "assets"),
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
ALLOWED_HOSTS = ['*']
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = []
LOCAL_APPS = [
'blog',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
/microblog/microblog/settings/local.py
DEBUG = True
/microblog/microblog/urls.py
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
import blog.urls
from . import views, settings
admin.autodiscover()
urlpatterns = [
url(r'^$', views.HomepageView.as_view(), name="home"),
url(r'^blog/', include(blog.urls, namespace="blog")),
url(r'^admin/', admin.site.urls),
# url(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.base.STATIC_ROOT}),
]# + static(settings.base.STATIC_URL, document_root=settings.base.STATIC_ROOT)
/microblog/microblog/views.py
from django.views.generic import TemplateView
class HomepageView(TemplateView):
template_name = "index.html"
/microblog/blog/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
class PublishedPostsMixin(object):
def get_queryset(self):
queryset = super(PublishedPostsMixin, self).get_queryset()
return queryset.filter(published=True)
class PostDetailView(PublishedPostsMixin, DetailView):
model = Post
/microblog/microblog/templates/_layouts/base.html
<!doctype html>
<html>
<head>
<title>{% block page_title %}{% endblock %}Microblog</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Welcome to my site!</h1>
{% block page_content %}{% endblock %}
</div>
</body>
</html>
/microblog/microblog/templates/index.html
{% extends "_layouts/base.html" %}
{% block page_content %}
<a href="{% url 'blog:list' %}" class='btn'>Read my blog</a>
{% endblock %}
THE RUNSERVER ERROR I'M SEEING IS:
Performing system checks...
System check identified no issues (0 silenced).
December 23, 2015 - 11:13:14
Django version 1.9, using settings 'microblog.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[23/Dec/2015 11:13:20] "GET / HTTP/1.1" 200 391
Not Found: /css/bootstrap.min.css
[23/Dec/2015 11:13:20] "GET /css/bootstrap.min.css HTTP/1.1" 404 2190
ATTEMPT AT PROBLEM DIAGNOSIS
Taking the 'Not Found' message from above, the path /css/bootstrap.min.css rather than /static/css/bootstrap.min.css has lead me to believe the problem is manifesting itself in the /microblog/microblog/templates/_layouts/base.html file here:
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
It appears that {{ STATIC_URL }} is not being interpreted to it's it set value of '/static/' and therefore the lookup path is /css/bootstrap.min.css rather than the expected /static/css/bootstrap.min.css. Yes, I have validated that the expected path and file does exist on the actual file system. Accordingly, when the page renders, it's just your standard HTML output without the CSS styling that I'm expecting. In the /microblog/microblog/templates/index.html file, the class="btn" is not working/rendering properly either.
I have read that this might have to do with the values of DEBUG and/or ALLOWED_HOSTS and of course I suspect my PATHS.
Let's deal with the paths first. It could be that best-practices dictate that I should adjust my current paths somewhat, please advise (lack of experience here), but for now I'm just following what I was told to do on the tutorial website. In that vein and since I'm not using hard-coded paths, I have confirmed the post-code-interpretation (base.py) of each of my paths, as well as the actual existence of each of these folders in my file system (see the DIRECTORY STRUCTURE block near the top of this post) as follows:
here() = /vagrant/PROJECTS/microblog/microblog/settings
PROJECT_ROOT = /vagrant/PROJECTS/microblog/microblog
root() = /vagrant/PROJECTS/microblog/microblog
TEMPLATES = [{'DIRS': = /vagrant/PROJECTS/microblog/microblog/templates }]
MEDIA_ROOT = /vagrant/PROJECTS/uploads
MEDIA_URL = ''
STATIC_ROOT = /vagrant/PROJECTS/static
STATIC_URL = '/static/'
STATICFILES_DIRS = [ /vagrant/PROJECTS/microblog/assets ]
With regards to DEBUG needing to be set to 'True', this is the case in my local.py file, which is imported when I run Django locally but not imported when I push code to production (local.py is excluded from production sync via .gitignore).
With regards to ALLOWED_HOSTS you'll see I currently have a value of '*' which may or may not be appropriate. I don't know, lack of experience.
I've noticed that running python manage.py collectstatic collects 0 files but I'm unsure why.
You'll notice that my /microblog/microblog/urls.py has some lines commented out of it, I've tried various things here to try to resolve the issue.
One further observation. The admin side of my project has the default styling typical of the Django Admin interface but this only became true when I enabled the STATICFILES_FINDERS called django.contrib.staticfiles.finders.AppDirectoriesFinder. I believe that's because this causes Django to go look where the files are for the admin app. Since these haven't been synced to the STATIC_ROOT location (because python manage.py collectstatic is failing), I'm assuming it's looking in the location where my VENV makes these files available (/home/vagrant/blog-venv/lib/python2.7/site-packages/django/contrib/admin). Can anyone confirm this? As for the front-end side of the project, that piece is obviously still having trouble.
I'm relatively new to Django and I'm very stuck on this problem. Essentially this boils down to getting static files working for my site as a whole and without that I'm kind of dead in the water as I will need static files functionality for other aspects of my project too. I don't know if there is a better way I should be troubleshooting or debugging. I sort of expect that I'd get a browser error page (since DEBUG=True) that would help me further narrow down the problem but I'm not getting this despite my DEBUG setting. I also don't know if there is a way to python manage.py runserver with parameters which would produce more debug output as to why I'm getting the 404.
Any assistance or advice with this problem as a whole will be greatly appreciated. If any further information is required, please request and I will post an update. Thank you in advance!
This is really the key point to look at:
[23/Dec/2015 11:13:20] "GET /css/bootstrap.min.css HTTP/1.1" 404 2190
The /static prefix is missing from /static/css/bootstrap.min.css.
As the documentation explains, you should include this in your template to use static files:
{% load staticfiles %}
And in modern versions of Django, instead of:
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
You should use:
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
This static template tag appeared in Django 1.4, and has been the preferred approach since.

Python build path based on current OS [css imports]

I am trying to link some CSS in my html (running a Django server) and the problem is that if running on Windows and using the \ (backslash) but then it wouldn't execute properly on Linux (since it uses / (slash)
What is the best way to modify the path in my base.html based on the current executing operating system?
For example if it's Windows it should be:
<link rel="stylesheet" href="{% static "\style.css" %}"/>
^
But on Linux:
<link rel="stylesheet" href="{% static "/style.css" %}"/>
^
First, configure STATIC_ROOT and STATIC_URL in yoursettings.py:
import os
# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
# Absolute path to the directory where ``collectstatic``
# will collect static files for deployment.
#
# For more information on ``STATIC_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
# URL to use when referring to static files.
#
# For more information on ``STATIC_URL``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#static-url
STATIC_URL = '/static/'
Then you should be able to use
{% static 'project/css/style.css' %}
which, as far as I know, will take care of compatibility.
Consider reading about managing static files.

Custom stylesheets in Django (1.3) admin

I've got several custom stylesheets that override default admin styles. They live in myproject/static/admin/css-extended. I'm overriding several of Django's default admin templates with templates that live in 'myproject/templates/admin'.
In the templates my stylesheet references are: {{ STATIC_URL }}/admin/css-extended/[stylesheet].css.
However, I can't get the custom stylesheets to pull through.
I've got the following url-related settings in settings.py:
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
I've got the following template context processors listed:
'django.core.context_processors.media',
'django.core.context_processors.static',
Can anyone help please?
Thanks
UPDATE:
I suspect the issue has something to do with the fact that my ADMIN_MEDIA_PREFIX is the same as the first part of the css-extended url ('/static/admin'). I guess Django is trying to find a directory called 'css-extended' in the core admin rather than in the project itself. But how do I get round this?
Are you having this problem on your local dev environment (with runserver)? If so, do you have the following in your urls.py?
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
Read the Django Docs for more.
Ok, I now think I know what's going on here. Hopefully this will clarify:
STATIC_ROOT is only used by the "collectstatic" management command, to figure out where to dump the static files it collects.
STATIC_URL is used by the dev server to define the URL at which the static files will be served.
STATICFILES_DIRS, which you haven't set, is used by both the dev server and the "collectstatic" management command to identify the locations of the static files to serve. In the case of the dev server, the files are served directly in place. In the case of the management command, the files are gathered and copied into STATIC_ROOT.
[Note: there's a convention here -- if you have /static subdirectories in your apps (not your project), they'll be picked up along with anything explicitly defined in STATICFILES_DIRS.]
You just need to add the following to settings.py:
STATICFILES_DIRS = {
'/absolute/path/to/myproject/static/',
}

django css file not recognised - wrong configuration?

in my app, i want to use a css file, but the tempalte doesn't 'know' where the file is, though i've configured it as in tutorials:
in the urls.py (the urls file in the root of the site, not belonging to an app)
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
in the template
<link href="/site_media/default.css" rel="stylesheet" type="text/css" />
in the settings:
STATIC_DOC_ROOT = '/site_media'
where can i be wrong?
Thanks
Check django-annoying, it's a very useful app with plenty of convenient decorators, middlewares and functions. If you add StaticServe middleware like that, Django will serve static if DEBUG = True without explicitly setting in urls.py.
MIDDLEWARE_CLASSES = (
'annoying.middlewares.StaticServe',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
Second, check your MEDIA_URL (in your case it's STATIC_DOC_ROOT, but you should use MEDIA_URL) and MEDIA_ROOT path. MEDIA_ROOT should point to absolute path to your static directory. This is how I do it in setttings.py:
import os
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
# MEDIA_ROOT will point to media directory where settings.py is located
MEDIA_ROOT = rel('media')
MEDIA_URL = '/media/'
You can use the same function to set path to your templates dir.
The document_root argument to static.serve needs to be the location of the file on the server filesystem, not the URL. So unless your css file really is in the /site_media directory on your disk, which seems unlikely, you want something else as STATIC_DOC_ROOT.

Resources