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
Related
My app consists of django and react, which at the end is bundled to static (.js) file.
My goal is to setup a nginx for it, but for now I just want to run in uwsgi to see if it works.
Aaaaand it does not work at all. I belive there is a issue with loading this bundle file which webpack is compiling.
Connection to uwsgi works, server is up and running, but when connecting to 127.0.0.1:8080 I get (in Mozilla):
The resource from “http://127.0.0.1:8080/static/frontend/main.js”
was blocked due to MIME type (“text/html”) mismatch
(X-Content-Type-Options: nosniff).
# and another
GET http://127.0.0.1:8080/static/frontend/main.js
HTTP/1.1 404 Not Found
Content-Type: text/html
X-Frame-Options: DENY
Content-Length: 3277
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Vary: Origin
Similar topic I found: Difference between static STATIC_URL and STATIC_ROOT on Django
and this: Django + React The resource was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
But messing with python manage.py collectstatic resolved nothing.
I have this lines of code to manage static files:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join('/app/label_it/front/static/frontend/')
And this is how I start my uwsgi connection:
python manage.py collectstatic --no-input
uwsgi --http 0.0.0.0:8080 --master --enable-threads --module label_it.wsgi
Beside collectstatic I've tried messing with <script src"static_file_path"></script> this static path with:
<script src="../../static/frontend/main.js"></script>
# and
<script src="{% static "frontend/main.js" %}"></script>
Which result in nothing.
Any clues appreciated !
EDIT:
My file structure:
Ok I just did some testing with my own server and django project to confirm my suspicion and I've come to the following conclusion: This error will happen if the path to the static file doesn't exist. Meaning that uwsgi cannot find this main.js file with the settings you have.
My suggestion would be to do the following to ensure your static files are being served correctly in a way that django knows where to look.
By default django searches inside each installed app for a static folder to find static assets. Because your project is not setup that way you have to specify additional directories where static files live.
This is what STATICFILES_DIRS is for.
In your settings.py put the following
STATICFILES_DIRS = [
BASE_DIR / 'label_it/front/static'
]
This will make all files inside label_it/front/static discoverable to django.
Now this means that
<script src="{% static "frontend/main.js" %}"></script>
will (hopefully) work.
additionally, remember to include your static urls in your urls.py file if you haven't already.
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
...
]
# static content urls
urlpatterns += staticfiles_urlpatterns()
Sidenote: STATIC_ROOT is intended to be the location where all static files will be collected to when you run python manage.py collectstatic.
As such it should be an empty directory, preferably in the root of your django project.
STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected')
The name of the folder doesn't really matter and I've used static_collected as an example.
If you run the command hopefully you'll see all the files in label_it/front/static/ copied there.
I have a frontend react app, after using npm run build it creates build folder with:
build
favicon.ico
index.html
service-woker.js
static
After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work.
In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" />
In my settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../frontend/build/static')
]
STATIC_ROOT = '/var/www/web/home/static/'
STATIC_URL = 'home/static/'
In chrome inspect in the headers element:
<link rel="icon" href="./home/favicon.ico">
How do I get it to display my web icon. Thankyou!
It is clear in documentation that Django collectstatic looks only for files in folders that are set in
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../frontend/build/static')
]
This will copy all files from your static folders into the STATIC_ROOT
directory.
your favicon is not in any of listed staticfiles directiories
Second thing is that Django static files are only accessible from full STATIC_URL path ( you cannot use just .home/ path)
Fix would be one of following
to simply add icon inside static folder
use ngnix to serve static files and add proper blocks ( prefered )
change STATIC_ROOT='/var/www/web/home/' and STATIC_URL = 'home/' ( note this way index.html and rest of files in home would be accessible as staticfiles)
I've encountered a problem that, even after an evening of trying , I've not yet been able to resolve.
For my project I have a single static directory, and I've included the css files for the 'login' page in there. Yet when I try to load the webpage I get a 404 error.
When I try to find the files with the 'findstatic' or 'collectstatic' commands the files get skiped. Its like the 'static' directory is invisible to django. I've even directly copies the 'Login' folder to 'static_root', but even then the program was Django was unable to find the files.
Does anyone have an idea what I am doing wrong?
My project folder looks like this:
* MPS (main folder)
* Scraper (app)
* Database (app)
* Templates
* Static_root
* Static
* Login
* css
* style.css
My settings.py has been configured like so:
STATIC_URL = 'static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/')
And I call the static files in the template with the following code:
{% load staticfiles %}
(...)
<link rel="stylesheet" href="{% static 'login/css/style.css' %}">
Your project folder structure looks a bit different from most Django projects. Traditionally it would look something more like this:
myproject/
urls.py
wsgi.py
settings.py
myapp/
static/
myapp/
css/
style.css
js/
index.js
manage.py
Notice that the app static files of myapp is within a subfolder called the same as the app folder. This is to easily namespace the files as you can read more about in the docs.
Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.
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' %}"
I have a MyApp/static/MyApp directory.
When I run ./manage.py collectstatic, I expect the MyApp directory be copied to STATIC_ROOT, but it doesn't.
I have DownloadedApp/static/DownloadedApp as well and its copied to STATIC_ROOT fine.
What am I missing?
What are the STATIC_ROOT, STATICFILES_FINDERS, and STATICFILES_DIRS in your settings.py?
When collectstatic is run, the default STATICFILES_FINDERS value django.contrib.staticfiles.finders.FileSystemFinder will collect your static files from any paths that you have in STATICFILES_DIRS.
The other default STATICFILES_FINDERS value django.contrib.staticfiles.finders.AppDirectoriesFinder will look in the /static/ folder of any apps in your INSTALLED_APPS.
All of the static files that are found will be placed in the specified STATIC_ROOT directory.
Check out this link to the collectstatic docs
And this link an explanation of the various static settings in settings.py
You can also use python manage.py findstatic to see which directories collectstatic will look in.
just do this and make the naming convention same
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
static directory contains all off your project assets
assets directory will create automatic when u run this cmd
python3 manage.py collectstatic
this will copy all static folder content into assets folder
hope this helps :)
That just happened to me and I accidentally put the app's static files directory in the .gitignore file. So on my local machine it got collected just fine, but in production the static files were actually missing (gitignored).
your are missing the STATIC_ROOT where your static files going to be copied just
add this line in your settings.py
STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')
your settings.py looks like this :
STATIC_URL = '/static/'
STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')
#added manully
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
remember to add STAIC_ROOT path in urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("" ,include("home.urls")),
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
After all of it you can run :
python manage.py collectstatic
it will create a staticfiles folder for you in your Dir
This happened to me because while investigating a bug occurring on certain dates, changed my computer date and time.
Hence it disturbed things like collectstatic, and also my browser history.
Don't change your computer date and time.
I was under the impression the comparison would be content based. It turned out to be date based. So, don't mess with your files after collecstatic.
One Quick work-around, although this does not fix it or explain WHY it's happening, is to:
go to your project's file directory & rename your project's
'static' folder to something else like 'static-old'
create a new,empty folder called 'static' in your project directory
now if you run python manage.py collectstatic it will see that nothing is
in your static folder and will copy ALL static files over.
if you have setup everything properly for static and you are using nginx then enter this command
sudo nginx -t
You will see error why your static files aren't being served and fix that specific error
In my case I gave wrong path in my nginx config
location /static {
root /home/ubuntu/myproject/app/static/;
}