STATICFILES_DIR does not work on Apache web-server - python

I'm testing one and the same application both on the default Django server and on Apache and I see a lot of big differences. I managed to resolve some of them, but at this moment I'm unable to resolve a major difference. So, in project settings.py file I have this code:
MODULES_DIR = BASE_DIR + '/system/modules/'
for item in os.listdir(MODULES_DIR):
stat = os.path.join(MODULES_DIR, item + '/static')
if os.path.isdir(os.path.join(MODULES_DIR, item)):
INSTALLED_APPS += ('system.modules.%s' % item, )
STATICFILES_DIR += (stat, )
APPS_DIR = true
This code is supposed to populate INSTALLED_APPS dynamically, based on the contents of BASE_DIR + '/system/modules/' folder. In other words, if there is a folder inside /modules, this folder becomes an application. Likewise, I build dynamically STATICFILES_DIR - in this case it is supposed, that every single folder/application (which is inside /modules folder) has a /static folder with static contents - js, css etc. For example, it may be such a construct:
\modules
\DefaultModule
__init__.py
urls.py
views.py
\static
test.js
\templates
DefaultModule.html
And DefaultModule.html in this example loads static files like this:
<html>
<head>
{% load static from staticfiles %}
<script type="text/javascript" src="{% static "test.js" %}"></script>
It is rather interesting, but on default Django server this logic works perfectly, so that when I go in my browser to localhost/DefaultModule/, I see a template DefaultModule.html loaded and I see test.js file loaded from http://localhost/DefaultModule/static/. However, on Apache the template is rendered too, but the test.js file is loaded from http://localhost/static/ what eventually results in a 404 NOT FOUND error. So, for some reason Apache server does not take into account STATICFILES_DIR. And yes I checked its (I mean STATICFILES_DIR) contents and it is the same. In both cases STATICFILES_DIR contains modules/DefaultModule/static/, but on Apache it is ignored for some reason. Hope someone can help. Thanks!

I think you should read the Django docs on static files. Looks like you're falling into the simple and old Django Static File Hosting an Apache
Check it out and let us know.

Related

Django admin wont load certain static files

I have a strange issue that's occurred on several django projects and I'm trying to figure out a fix for it. For some reason, all the static files for the admin area load properly including the js, css, and images but 2 files for the side nav bar (which are in my static directory along with everything else) wont load. The files are the nav_sidebar.css and nav_sidebar.js.
I've figured out a work around and added these inline in the admins base.html template and deleted the links to these files. This works but it's kind of ridiculous that it manages to load all other static assets fine but not these particular files. I have my static root and directories set up properly, have nginx pointing to the correct static directory, and have done collect static and restarted the server. Everything I could possibly think of but it doesn't work.
Considering this has happened on 3 straight projects, I think this is some kind of bug rather than an error on my end.
So I was able to answer my own question in the end and for anyone else that comes across this problem here are the steps I took.
For the admin static files, before you run collect static are being sourced directly from the wherever your python(versionNumber)/site-packages/django/contrib/admin/static is located. Unless you run collect static, or manually copy and paste them into your static files directory, these admin files wont be there.
Now I'm sure this is basic knowledge for any django user and I even did this and the error still persisted. What I found, is that I set my static urls up like:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
And for some reason, django was still sourcing the admin files from that same directory the django source is located. So I simply changed the url path and static root to:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And ran manage.py collectstatic again and that fixed my admin area and everything is working properly now.
These two files are introduced in django 3.1 for nav_sidebar feature. In admin/base.html, it says:
{% if not is_popup and is_nav_sidebar_enabled %}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/nav_sidebar.css" %}">
<script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script>
{% endif %}
is_nav_sidebar_enabled by default is enabled. Did you put something in the root urls.py to disable that?
something like:
admin.site.enable_nav_sidebar = False in your root urls.py?
The doc about the new nav_sidebar feature is here

Django static files do not resolve constant 404 errors

I am new to Django current version I'm running is 1.11 with python 3. I have configured the static file stuff as the docs suggest. Inside installed apps I have 'django.contrib.staticfiles'
nonprofit/nonprofit/settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIR = (
os.path.join(BASE_DIR, "static/"),
)
And django seems to be working as far as putting the right path in the template. Though even if I hardcode the path into the template the browser still gives a 404 not found.
I have a base.html template, with some css.
{% load staticfiles %}
<!--Bootstrap-->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<link rel="stylesheet" href="/static/css/bootstrap-theme.css">
My directory structure is --
nonprofit
- goals
- nonprofit
- static
- css
bootstrap.css
bootstrap-theme.css
- templates
base.html
db.sqlite3
manage.py
From the browser it shows both 404 not found errors as well as not being able to go straight to the files-
GET http://127.0.0.1:8000/static/css/bootstrap.css 127.0.0.1/:19
GET http://127.0.0.1:8000/static/css/bootstrap-theme.css 127.0.0.1/:20
I don't think the problem is with django because it shows the right path, but even the hardcoded one cannot be accessed through the browser. I'm running the development server. Whats going on with this stuff? Do I have something wrongly configured or lacking configuration? Any help is appreciated. I have looked at all the suggested posts and have tried various things without any good results.
The setting name is STATICFILES_DIRS. You are missing the S.

Is there a way to load file that is under templates folder on Django HTML?

I could load css file on Django html like this
{% load staticfiles %}
<link rel="stylesheet" href="{% static "css/style.css" %}">
I wonder why I can't load css file that is under templates folder.
<link rel="stylesheet" href="css/style.css">
Is there a way to load file that is under templates folder on Django HTML?
Why does Django wants me to put {% static "css/style.css" %} this format on all static files? Is it because much faster to load?
What If I load file that is under templates folder? Is it slow to load?
Templates and static assets are two differents types of assets that need to be managed differently for security purposes.
All js, css and images files need to be provided to clients in order for your website to be working. They are handled from the client side so they need to be available. So static asset folder is made to be available, if you check view source and follow the link of these assets you'll see they can be opened directly in your broswer.
Templates however are used by django itself to generate the output that is set via your views. When a user opens a page, he doesn't access the template itself but the rendering made by django. So the template folder isn't accessible to end user by design, including the files that are in it. So the only things a user can access from a django application are the responses given by the views, that are based on urls patterns and the templates, and assets that are in static folder. So you can't, and shouldn't, link to static assets from anywhere else but your static folder.
As I can see it, you have missed the concept of the templates and the static files in Django.
First of all, there are two independent mechanisms: loading a template file (your future HTML file) and loading your static files (css, js, images).
When loading a template Django uses TEMPLATE_LOADERS (docs), which are basically defined in your settings.py as:
TEMPLATE_LOADERS = (
# Loads templates from DIRS setting:
'django.template.loaders.filesystem.Loader',
# Loads templates from your installed apps:
'django.template.loaders.app_directories.Loader',
)
You can define a location of yout templates by setting DIRS (if you are using Django >= 1.8) or TEMPLATE_DIR (if Django < 1.8). There are several more steps in rendering your template such as: template context processors and so on, but it is all listed in the documentation.
Now about static files.
Static files are served by django.contrib.staticfiles app (docs) when DEBUG = True. In production it is done by Nginx, Apache or other Http-Servers.
When loading a static file Django uses STATICFILES_FINDERS. They are usially defined as:
STATICFILES_FINDERS = (
# Loads static files from STATICFILES_DIRS:
"django.contrib.staticfiles.finders.FileSystemFinder",
# Load static files from installed apps:
"django.contrib.staticfiles.finders.AppDirectoriesFinder"
)
There are two main settings to care about: STATIC_URL and STATICFILES_DIRS.
STATIC_URL is basically just a prefix, which is used to get your static files. It is almost always just '/static/'. And in STATICFILES_DIRS there are paths to your static files folders. It is sometimes extended to include node_modules, bower_components or things like that.
When dealing with static files in templates you need to append your STATIC_URL to your file's URL. The easiest way to do that is {% static %} tag.
A lot of confusion comes with STATIC_ROOT. It is just a path, where all your static files will be collected in production after running collectstatic management command.

Django at PythonAnywhere doesn't recognize static url

The problem looks similiar to the problem here:
Pythonanywhere, how to use static files? url? ,but I cannot comment there.
I've started learning Django and when everything worked on localhost that on PythonAnywhere it does not.
At projectname/settings.py I've set:
STATIC_ROOT = "/home/*username*/*projectname*/Static/"
STATIC_URL = "/s/"
and even URL's from static folders in apps.
After trying to run
python3 manage.py collectstatic
every file *.js, *.css and images were coppied to the projectname/Static folder.
But... none of them were recognized after launch of the app.
I've set
{% load static %}
used tags
{% static "assets/css/theme.css" %}
At the source code I can see the proper link to css file:
<script src="/s/assets/js/seen.min.js"></script>
And everything would be fine, but the "/s/" isn't recognized by django and it tries to find the view in urls.py.
After opening the link to: username.pythonanywhere.com/s/assets/js/seen.min.js I've got standard, debug 404 page with the path of urls.py tries.
How to solve this annoying problem?
You need to add a static file mapping on the web app. Look for the "Static files" heading on the web app tab.
From what I can tell of your setup, you'd need to put "/s/" for the URL and "/home/*username*/*projectname*/Static/" for the directory.

How to link resources in a Django page

Let's suppose I have an HTML page (base.html) that must include one JavaScript file.
<script type="text/javascript" src="/js/main.js"></script>
It is my understanding that a Django project is not hosted in a public folder. Rather, requests are routed to views.py which generates a response.
Let's suppose my project directory looks like this
- project
- project_app
- views, models, ecc…
- templates
- base.html
- css
- main.css
- js
- main.js
How come base.html can reference main.css and main.js? If I access myserver.com/js/main.js this should not return anything (as the template folder is not public). Yet the browser need to access those file and I need to include them.
Do I need to write a specific URL rule to redirect requests to /js/main.js to the actual js file or what sort of magic can make a simple html include works?
The usual method is to keep your CSS, javascript, and similar files in a static folder and serve them to your html. General Django documentation can be found here.
In a nutshell, your directory will look like this:
- project
- project_app
- views, models, ecc…
- templates
- base.html
- static
- css
- main.css
- js
- main.js
Then, your base.html will reference the file using:
<script type="text/javascript" src="/static/js/main.js"></script>
The docs I referenced at the top show how to serve static files in production. Lots of people use a content delivery network (CDN) to serve their static files. Amazon's S3 service is an example of this. Then, you'll change the STATIC_URL setting in your settings.py to your S3 bucket (or similar network). You can then reference the STATIC_URL in your templates.
{% load static %}
...
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
...
You'll use commands like ./manage.py collectstatic to collect your static files and move them to your CDN at certain times. Basics of collectstatic can be found here.
You need to put all your static files in STATIC_ROOT folder by using command django-admin.py collectstatic and serve this folder. More details and explanation you can find here:
https://docs.djangoproject.com/en/dev/howto/static-files/#managing-static-files-css-images

Categories