I made static folder in my root project.
in settins.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Install npm library under static directory.
myproject/static$ npm -i js-cookie
then There comes the files like this
myproject/static/node_modules/js.cookie/dist/js.cookie.min.js
then run server
myproject$ python manage.py runserver
then use in template.html
However this shows the error
GET http://localhost:8000/static/node_modules/js.cookie/dist/js.cookie.min.js net::ERR_ABORTED 404 (Not Found)
I have two quesitons.
Is it good practice to use npm library under django project??
Maybe runserver doesn't use mypoject/static?
Related
I have developed a web app in Django and deployed it then I found out that admin page is not loading with CSS. I was gettting the admin page with css in local server but not when I deployed it.
Even after using
python manage.py collectstatic
It's not loading with css.
Here is my settings.py code
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
Here is the static files linkage part:
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'first_app/media')
I am not able to figure out why it's not linking the css part even after the above code
Django version: 3.1
Python version : 3.8.3
Please could anyone help me out in this
Thank you
If you are in production you have to run:
python manage.py collectstatic --noinput
But you also must serve the static files through your web server. The easiest way to do this is with WhiteNoise: http://whitenoise.evans.io/en/stable/
This will work with Nginx, Heroku, etc. So it's a very flexible solution.
Setup looks fine. You may need to run collectstatic in production environment again.
add this code to your setting.py
DEBUG = False
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
and after running run this command :
python manage.py collectstatic --noinput
and deploy project with webservices like nginx or ...
and add staticfiles path to your webservice config
for nginx somethins like this
location /static/ {
alias /home/{{your project path }}/static/;
}
Django doesn't serve static files in production, you are supposed to use other methods for serving your files either with apache2 or nginx. If you are good or know some docker container here is a tutorial that explains how to deploy Django https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/
upstream hello_django {
server web:8000;
}
server {
listen 80;
location / {
proxy_pass http://hello_django;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /staticfiles/ {
alias /home/app/web/staticfiles/;
}
}
Please check also django doc here https://docs.djangoproject.com/en/3.1/howto/static-files/deployment/
Please check this post for apache2 without docker containers https://programmingzen.com/serving-django-static-files-through-apache/
Just do a trick here. After running collectstatic command, you'll get admin statics in staticfiles folder. Just cut it there and paste in static folder and i don't know why Django doesn't support admin static in production. If anyone knows this, welcome for your answers
You did not mention that on which server you're trying to deploy your application If you're deploying your application on Heroku then you need to install whitenoise, which I have already explained here, but if you're using any other server then you can this answer https://www.thecodecity.com/2020/05/django-admin-static-files-not-loading.html
Try this in settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = BASE_DIR / 'staic'
MEDIA_ROOT = BASE_DIR / 'media'
STATICFILES_DIRS = [BASE_DIR / 'static']
Django 3.1 Documentation
Just insert this line in settings.py --> INSTALLED_APPS:
django.contrib.staticfiles
This is unrelated, but I spent minutes trying to get this.
If you are in development and using a virtual environment, remember to start your virtual environment.
Got a Django project named django_server. When I run
python manage.py runserver
the page shows up as expected
Then, if I run
gunicorn django_server.wsgi:application --bind 0.0.0.0:8000
The page shows without styling
Checking the console, can see the following errors for both .css and .js files
The resource from
“http://0.0.0.0:8000/static/....css” was blocked
due to MIME type (“text/html”) mismatch (X-Content-Type-Options:
nosniff).
In the terminal where the gunicorn command was executed, can read
NOT FOUND: /static/rest_framework/css/bootstrap.min.css
NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css
...
In settings.py I mention
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
This is the folder structure
Checked the permissions in static folder (ls -l)and they show as
drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static
Checking the permissions in the files where the problem happens and
Added also to settings.py
import mimetypes
mimetypes.add_type("text/css",".css",True)
mimetypes.add_type("text/javascript",".js",True)
But the error remains.
You need to run python manage.py collectstatic.
On your settings.py I recommend you to use whitenoise to serve your files.
1) pip install whitenoise
2) Add STATICFILES_STORAGE on settings.py
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
3) Add to your MIDDLEWARE on settings.py
`MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
...
]
I'm not able to get my django project to run with whitenoise and compressed staticfiles (including libsass). In links below, I read that it's only possible by offline compression of needed staticfiles. But when I started up the docker container, running compress command
docker-compose -f production.yml run --rm django python manage.py compress
gives me error:
ValueError: Missing staticfiles manifest entry for 'sass/app.scss'
While trying to request the site gives me following error (as expected?):
compressor.exceptions.OfflineGenerationError: You have offline compression enabled but key "..." is missing from offline manifest. You may need to run "python manage.py compress"
Settings are as follows (build with cookiecutter-django, see link for complete code base below):
STATIC_ROOT = str(ROOT_DIR("staticfiles"))
STATIC_URL = "/static/"
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"]
COMPRESS_PRECOMPILERS = [("text/x-scss", "django_libsass.SassCompiler")]
COMPRESS_CACHEABLE_PRECOMPILERS = (("text/x-scss", "django_libsass.SassCompiler"),)
COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True)
COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage"
COMPRESS_URL = STATIC_URL
So after searching the internet for 1 day; I'm stuck... Thx for any help or suggestion!
Code base: https://github.com/rl-institut/E_Metrobus/tree/compress
which is build with cookiecutter-django-foundation
including the following changes to config/setttings/production.py:
COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" # Instead of pre-set "storages.backends.s3boto3.S3Boto3Storage"
COMPRESS_ROOT = STATIC_ROOT # Just in case
COMPRESS_OFFLINE = True # Needed to run compress offline
Possible related links:
Whitenoise and django-compressor cause 404 for compressed files
Possible to use WhiteNoise with Django-Compressor?
Django staticfiles not found on Heroku (with whitenoise)
https://github.com/django-compressor/django-compressor/issues/486
EDIT
Solved it using Justins answer (see below, with additonal changes).
My mistake was trying to compress files with already running container, giving me the error above. After changing Dockerfile with following lines (Notice the duplicate collectstatic cmd!):
python /app/manage.py collectstatic --noinput
python /app/manage.py compress --force
python /app/manage.py collectstatic --noinput
/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app
and rebuilding image everything worked like a charm :)
Additionally, diverging from settings above, I had to set COMPRESS_ENABLED=True in my settings/env file.
I just had the same problem.
Add this to project/compose/production/django/start
python /app/manage.py compress --force
i.e.
python /app/manage.py collectstatic --noinput
python /app/manage.py compress --force
/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app
this is weird but it work very well.
collect and compress static files by whitenoise
python manage.py collectstatic --clear
set COMPRESS_STORAGE = 'compressor.storage.BrotliCompressorFileStorage'
to make .br files in CACHE directory
python manage.py compress --force
set COMPRESS_STORAGE = 'compressor.storage.GzipCompressorFileStorage'
to make .gzfiles in CACHE directory
python manage.py compress --force
to add new compressed files to whitenoise: manifest.json, manifest.json.gz,
manifest.json.br
--no-post-process option is to tell whitenoise not to compress static files again.
python manage.py collectstatic --no-post-process
make sure to run the commands in order.
to test if whitenoise is working
python manage.py runserver --nostatic
I am trying to set up a development version of a Django Rest (1.11) application on a mac.
I have run the python manage.py collectstatic command and this resulted in the files being copied into a 'static' folder.
However when I run the application (python manage.py runserver) none of the static files load in the browser (no css). The Network tab shows the status of the static files as 404.
My settings.py file has the following:
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR + '/abba_rest/static/'
Appreciate any advice on how to debug this issue.
I got the static files to load by using the --insecure flag when starting the server;
python manage.py runserver --insecure
I have a Django app on Heroku. I am having some problems with static files (they are loading in one Heroku environment but not another), so I tried the debug command recommended here.
$ heroku run python manage.py collectstatic --noinput
Running `python manage.py collectstatic --noinput` attached to terminal... up, run.8771
OSError: [Errno 2] No such file or directory: '/app/{myappname}/static'
Here is my settings.py, which is the same thing Heroku recommends:
import os
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
I get the error whether or not I actually have a directory "static" at the root level in my Git repo (tested it both ways).
Any ideas?
It's looking for a folder named 'static' that's next to the settings.py, i.e. in the project folder, not at the root of the git repo.
git root/
git root/{app name}
git root/{app name}/settings.py
git root/{app name}/static/ <- this is what you're missing
Note that empty folders aren't tracked by git, so you'll have to put a blank file in there if it's empty. Alternatively, remove the STATICFILES_DIRS setting until you need it.
I just had this same problem, and here's the solution that worked for me:
I changed:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
to:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'myappfolder/static'),
)
#joerick's answer above is the thing. However, if you do not want to place another 'static' folder (git root/{your app}/static), you might consider changing the BASE_DIR variable that is initially supplied by django-admin makeproject:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
which is just the (git root/) directory