django static files do not work for one application only - django

My django application works well except for one application, all the static files are not loaded.
That happens on this url: http://localhost/db_mgmt/add/dg/. The template is loaded, but no css, no js.
When I look at one of the errors, the browser tries to load the page http://localhost/db_mgmt/add/static/jquery.min.js but the link should be: http://localhost/static/jquery.min.js
These files are loaded in base.html and work everywhere else...
Example of inclusion in base.html:
<script type="text/javascript" src="{{ STATIC_URL }}jquery.min.js"></script>
Here is my settings.py if it helps:
# Django settings for europolix project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
import os
#root of the project
PROJECT_ROOT=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
#root of templates
TEMPLATE_ROOT=os.path.join(PROJECT_ROOT, 'templates')
#root of media files (import / export files)
MEDIA_ROOT=os.path.join(PROJECT_ROOT, 'media')
#root of static files (css, js, jquery...)
STATIC_ROOT=os.path.join(PROJECT_ROOT, 'static')
#WEB_ROOT=url of WSGIScriptAlias given in the apache configuration file (/etc/apache2/apache2.conf in Lubuntu 13.04)
#example: WSGIScriptAlias /europolix /var/www/europolix/europolix/wsgi.py -> WEB_ROOT="/europolix"
#in the apache configuration file, you must update the alias for static files as well
#ex: Alias /europolix/static /var/www/europolix/static -> WEB_ROOT="/europolix"
WEB_ROOT="/europolix"
#local
WEB_ROOT=".."
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.actrence.com/media/", "http://example.com/media/"
MEDIA_URL=WEB_ROOT+'/media/'
# URL prefix for static files.
# Example: "http://media.actrence.com/static/"
STATIC_URL=WEB_ROOT+'/static/'
# Additional locations of static files
STATICFILES_DIRS=(
STATIC_ROOT,
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
TEMPLATE_DIRS=(
TEMPLATE_ROOT
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
If I print those variables in my view I have the following paths:
PROJECT_ROOT /var/www/europolix
STATIC_ROOT /var/www/europolix/static
STATIC_URL ../static/
WEB_ROOT ..
Thanks in advance for your help.
Edit :
The variable WEB_ROOT is relative in local. Could it be the problem?
The variable searches in the parent directory (am I right?). So the applications with only one "child" in the url work (http://localhost/act or http://localhost/export) but not the applications with many "children" (e.g.: the one above, http://localhost/db_mgmt/add/dg/)
urls.py of the export app:
urlpatterns=patterns('export.views',
url(r'^/?$', 'export', name='export'),
)
urls.py of the db_mgmt app that does not work well:
urlpatterns=patterns('db_mgmt.views',
url(r'^add/(?P<field>\w+)/$', 'add', name='add'),
url(r'^form_add.html/(?P<field>\w+)/$', 'form_add', name='form_add'),
)

We would need to know more about the differences between the applications that work and the application that is giving you trouble

As I thought, the problem, one of the problems was about the WEB_ROOT variable.
Here is how I fixed it:
WEB_ROOT="http://127.0.0.1:8000"
Another problem was the path of the template of my application db_mgmt:
url="/db_mgmt/form_add.html/"+field+"/"
I had to remove the first slash to have it work:
url="db_mgmt/form_add.html/"+field+"/"
Solved :).

Related

How to server favicon.ico with Django and Whitenoise

I use whitenoise for static files and it works fine.
But how can I serve the /favicon.ico file?
There is a setting called WHITENOISE_ROOT, but I don't understand how to use it.
I would like to keep my nginx config simple and serve all files via gunicorn
If you want those files to be managed by collectstatic
Let's assume after running collectstatic, your favicon.ico file ends up being copied in a root subdirectory, located in your STATIC_ROOT directory.
Then, with:
WHITENOISE_ROOT = os.path.join(STATIC_ROOT, 'root')
Whitenoise will serve all files in STATIC_ROOT/root/ at the root of your application.
In your case, STATIC_ROOT/root/favicon.ico will be served at /favicon.ico.
If you don't want those files to be managed by collectstatic
You can have a root_staticfiles folder in your BASE_DIR which simply contains the static files you want to serve at /.
WHITENOISE_ROOT = os.path.join(BASE_DIR, 'root_staticfiles')
In this case, Whitenoise will serve all files in BASE_DIR/root_staticfiles/ at the root of your application.
Update about pathlib (2022-10-04)
Since a while now, the default settings.py Django creates uses pathlib. To be consistent with it, one may replace os.join calls with / operators, eg.:
WHITENOISE_ROOT = STATIC_ROOT / 'root'
You could as per this answer by hanleyhansen add the following line in a base template (used by all further templates):
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
Or you could write a redirect view like this answer by wim with some little modification:
from django.views.generic.base import RedirectView
from django.conf.urls.static import static
re_path(r'^favicon\.ico$', RedirectView.as_view(url=static('favicon.ico'), permanent=True))
I have a django app that uses Whitenoise (hosted on Heroku) and serves my favicon from a separate folder from my static files.
Make a folder root_files at path BASE_DIR/root_files.
In settings.py:
WHITENOISE_ROOT = os.path.join(BASE_DIR, 'root_files')
For a real-life code example checkout Mozilla's Bedrock repo. They have favicons in BASE/root_files and configure WHITENOISE_ROOT in settings.py

Django starts putting a slash in front of my static url relative path in 3.1

I had this code that worked ok in 3.0.8
<script src="{% static 'js/main.js' %}"></script>
with the value in settings:
STATIC_URL = (
"static/" # /static/ for django web development, static/ for django-bakery build
)
when building with bakery it works only if I supply the relative path.
But since 3.1, as per their release notes: The STATIC_URL and MEDIA_URL settings set to relative paths are now prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This change should not affect settings set to valid URLs or absolute paths. (https://docs.djangoproject.com/en/3.1/releases/3.1/#backwards-incompatible-3-1) it puts a / in front of my static url and the build fails.
Any ideas how to avoid it? I use django bakery to bake the site into a single file, no server.
Update: django-bakery will build without errors, but then the index file will have the script like this:
<script src="/static/js/main.js"></script>
which when you open the index.html, you will receive a 404, /static/js/main.js not found. while if you replace it with static/js/main.js it will work, since the static folder is in the same folder as the index.

Django Appending Slashes to Static File URLs on OpenShift

I am attempting to deploy a Django 1.6 application on OpenShift using the Python 3.3 cartridge, but I have run into problems with static files. I have had partial success with the OpenShift IRC channel, tutorials/templates (for example), and previous StackExchange questions (for example), but nothing has completely resolved the problem.
When I request the static content by URL (e.g. 'mydomain.com/static/stylesheet.css' or 'mydomain.com/static/icons/cog.svg') I can see them perfectly fine. When static files are used as SVG data for icons, they show up fine. Only when linking to a stylesheet have I run into problems. I use the following to include CSS in my template:
<link type="text/css" rel="stylesheet" href={% static "stylesheet.css" %}/>
I have loaded the static files tag set with {% load staticfiles %}. Instead of seeing the stylesheet at /static/stylesheet.css, Django (I assume that it is Django, not Apache) looks for it at /static/stylesheet.css/ (note the trailing slash). This causes the request to fail with a 404 status code. The same thing occurs when I use other file extensions (I have tried .txt, .css, and .svg) or link to a file contained in a subdirectory of static. It is only in this circumstance that an extra trailing slash is appended.
It is my understanding that Django appends a trailing slash to a URL in the event that the URL does not match any of the patterns defined in urls.py. Is it possible on OpenShift to configure Apache so that it directly handles all requests to URLs of the form /static/*? I have an .htaccess file in the wsgi directory with the commands
Rewrite Engine On
Rewrite Rule ^application/static/(.+)$ /static/$1 [L]
but this does not solve the problem. I have also tried using a rewrite rule for just the stylesheet as well as a few things with Alias but have had no luck there, either.
Should Django be getting the requests for these static files at all? I have confirmed that DEBUG is being set to False in my settings.py file, and make no mention of django.views.static.serve in my urls.py file. Here are the relevant parts of settings.py:
STATIC_URL = '/static/'
if 'OPENSHIFT_REPO_DIR' in os.environ:
STATIC_ROOT = os.path.join(os.environ.get('OPENSHIFT_REPO_DIR'),
'wsgi', 'static')
else:
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
I do not set values for STATICFILES_DIRS or STATICFILES_FINDERS because at present I'm only dealing with static files found at STATIC_ROOT. The OpenShift project looks like
~/app-root/runtime/repo/wsgi/
.htaccess
application
openshift/
settings.py
manage.py
#And so on.
static/
stylesheet.css
icons/
cog.svg
#More icons here.
This is my first time trying to deploy and I am stuck on this stumbling block. Does anyone know what I am doing wrong?
Instead of href={% static "stylesheet.css" %}, try href="{% static 'stylesheet.css' %}"

google app engine not loading admin static media files

I am new to django. I am using Google App-engine and Google CloudSQL to serve a django1.2 project. I've been following the tutorial here and have hit a snag.
I enabled the admin back end in my settings.py, but when I go to http://www.examplesite.com/admin/ the css files aren't found.
The admin html page loads fine, but the static files give a 404.
Here's my app.yml:
application: myapp
version: 1
runtime: python27
api_version: 1
threadsafe: true
libraries:
- name: django
version: "1.2"
builtins:
- django_wsgi: on
I left these as default in settings.py:
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
I know the files are located at google_appengine/lib/django_1_2/django/contrib/admin/media/
Do I need to copy those static resources into my project directory somewhere? Or do I have a setting wrong?
In GAE you need to make the static files accessible in your app.yaml
https://developers.google.com/appengine/docs/python/config/appconfig#Static_Directory_Handlers

Django static files stop working if turn on debug

urlpatterns = patterns('',
# Examples:
url(r'^$', 'core.views.homepage', name='homepage'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
That's my urls.py
The static file works if I disable the DEBUG, and doesn't work If I turn it back on.
Part of my settings
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Really strange to me, can anyone help?
No, STATIC_ROOT is not served by Django ever. In production (debug off), it is expected that your web server will serve this directory directly. In development (debug on), you shouldn't have this directory or anything in it, anyways.
Let me say that again for emphasis. You are never supposed to directly save any assets in STATIC_ROOT. This directory is solely for the output from the collectstatic management command. All assets in your project are supposed to be saved in the static directory of the particular app it belongs to.
Now, of course, you'll often have assets that are not directly related to a single app, but rather your entire project as a whole. For this scenario, you create a separate directory in your project and place all common assets there. You then add this directory to the STATICFILES_DIRS setting.
In development, Django will serve anything in that directory, and in production, the collectstatic management command will pull assets from that directory into STATIC_ROOT.