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.
Related
Since I had started Django, I'm tackling some ridiculous problems. Recently, when I start a new project and I run it on the server, Django's admin CSS is not loaded. The last project I ran on the server, after a while it was okay, and the real Django admin template was there and the CSS was loaded and it was working. But this time again the same problem happened and I don't know how to solve it cause the project here is the photo is raw, with no special code.
I don't know if it's Chrome problem or not, but I have tried it on other browsers and it was the same thing.
I would be glad if you can help me
the answer I found was to change STATIC_URL = 'static/' in settings.py to STATIC_URL = '/static/'. Only one '/' may change your whole admin appearance. This problem may not happens to everyone but running code in Pycharm, I had been tackling it for such a long time.
If this problem is happening locally, then just change your settings.py
DEBUG = True
#...
#...
STATIC_ROOT = YOUR_STATIC_ROOT_DIRECTORY
Then run collectstatic, make sure you have a proper STATIC_ROOT directory which is also in your settings.py file
python manage.py collectstatic
If you have deployed your app on a production server then, you have to follow certain things in order to get stylesheet and javascript files.
Firstly
In your urls.py you need to add this code
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + \
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Then you have to use a third-party media file server(CDN) Like AWS S3 or you can serve your css, js or media files from your Django server
If you don't want to use AWS S3, then you can either send css/js using your django app (which is not ideal to do), or you can use nginx or apachee to send your css/js
For Nginx to send js/css
You have to add a Static and Media File Root that can be accessed by your django application, I usually use /var/www/ to serve static and media from any Linux server
STATIC_ROOT = '/var/www/static'
MEDIA_ROOT = 'var/www/media'
Then if you are using nginx
server {
server_name domainname.com;
access_log off;
location /static/ {
root /var/www/static;
}
location /media/ {
root /var/www/media;
}
If it is still not working, then your django app might not be able to use the given static_root and media directory, make sure your app has access to them
If you want to send your js/css from your django app (Better not to do in production)
Then
To install whitenoise
pip install whitenoise
In your settings file
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
It's my first time I am trying to deploy django project to Digital Ocean droplet(instance) and set up with Gunicorn and Nginx. I'v got problem with static files because there are not loaded. It seems I messed things up because in tutorials static is usually located in (in my case) glboy/ and localy in my project it was located in glboy/app/. So I now there is folder /root/glboy/static and everything is copied there by python manage.py collectstatic . I can't understand what is wrong. I tried various things and restarted after every change sudo service nginx restart but nothing helped. What is likely to be wrong?
In sudo nano /etc/nginx/sites-enabled/closer:
location /static/ {
root /home/root/glboy/;
expires 30d;
}
In sudo nano /etc/nginx/sites-available/default:
location /static/ {
root /home/root/glboy/;
expires 30d;
}
In settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
EDIT:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Structure is like that. I am not sure what is before in unix. As far as I understand it's like home/root/
glboy/
app/, closer/, denv/, static/, manage.py, myapp.log
EDIT2: Main tutorial I'v been following if helps https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04
please help me on this docker django configuration for serving static files.
my Django project running on Docker got some issues with delivering static files.
All static files for admin view is loading fine, but static files for client web view is throwing 404 Not found Error.
This is my docker.yml configuration details:
web:
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- ./web:/usr/src/app
ports:
- "8000:8000"
env_file: .env
command: python manage.py runserver 0.0.0.0:8000
postgres:
image: postgres:latest
volumes:
- /var/lib/postgresql
ports:
- "5432:5432"
update
This is the admin static file url will look like :
http://developer.com:8000/static/admin/css/base.css
and this is how client static file url looks like:
http://developer.com:8000/static/css/base.css
Where those admin folder in static directory is creator by running django command collectstatic
I have used this setting previously, and was working fine. But when I moved the project root folder to another directory seems have this issue.
I am totally stuck here, many many thanks for all your help and feedback.
This was issue with the STATICFILES_DIRS configuration in the settings.py file.
This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.
Following was the configuration in my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
Now I updated this code to:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
And every files is loading fine.
Reference Link
Use Whitenoise to make your life easier when dealing with static files in django.
1.If you are using docker-compose,add whitenoise to your requirements.txt file:
whitenoise==3.3.1
2.Add whitenoise to your middleware apps inside settings.py
MIDDLEWARE_CLASSES = [# 'django.middleware.security.SecurityMiddleware','whitenoise.middleware.WhiteNoiseMiddleware',# ...]
make sure that you add this below your security.SecurityMiddleware app
3.Finally, change the following variables inside settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR,'<app_name>/static'),os.path.join(BASE_DIR, 'static'),)
Be sure to replace with the name of your app. Note that this only applies if your static files are stored in(for example) my_project/app/static/app/.
Otherwise if your static folder is located in my_project/app/static:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Lastly disable the built-in django static file server as follows:
INSTALLED_APPS = [
# ...
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
# ...]
As you have moved your project to another directory, there is a possibility that the path of your static directories are also different now. Django in most scenarios use apache, nginx or some other web servers to serve static files. One point to notice is that your static directory should be accessed publicly. I had gone through a problem like this before. What I did was I moved static dir to document root mentioned in apache config file.
So move your static files to the doc root of apache and update static directories in settings.py to refer to the static directory in your apache doc root. I hope this helps.
What are the differences of these three static url?
I am not sure if I am right, I am using the MEDIA_ROOT to store my uploaded photos (via models.ImageField())
However, I created a JS script to my admin and in admin.py. I defined the media as below:
....
class Media:
js = ('/admin/custom.js', )
and my settings.py:
....
STATIC_ROOT = "/home/user/project/django1/top/listing/static"
and I added the custom.js to STATIC_ROOT/admin/custom.js, but it is not working. Throwing 404 not found error.
And then I change the STATIC_ROOT to STATICFILES_DIRS, and it works!!
....
STATICFILES_DIRS = "/home/user/project/django1/top/listing/static"
So, I am not understand what is going on here. In fact, I just don't understand what is the difference between STATIC_ROOT and STATICFILES_DIRS.
Currently I am testing Django in my machine via virtualenv, not deployed yet, is it the reason STATIC_ROOT not working??
Development
STATIC_ROOT is useless during development, it's only required for deployment.
While in development, STATIC_ROOT does nothing. You don't even need to set it. Django looks for static files inside each app's directory (myProject/appName/static) and serves them automatically.
This is the magic done by manage.py runserver when DEBUG=True.
Deployment
When your project goes live, things differ. Most likely you will serve dynamic content using Django and static files will be served by Nginx. Why? Because Nginx is incredibly efficient and will reduce the workload off Django.
This is where STATIC_ROOT becomes handy, as Nginx doesn't know anything about your Django project and doesn't know where to find static files.
So you set STATIC_ROOT = '/some/folder/' and tell Nginx to look for static files in /some/folder/. Then you run manage.py collectstatic and Django will copy static files from all the apps you have to /some/folder/.
Extra directories for static files
STATICFILES_DIRS is used to include additional directories for collectstatic to look for. For example, by default, Django doesn't recognize /myProject/static/. So you can include it yourself.
Example
STATIC_URL = '/static/'
if not DEBUG:
STATIC_ROOT = '/home/django/www-data/example.com/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
You can find these settings in the Django documentation. Here are my own definitions and quotations from the documentation:
MEDIA_ROOT is the folder where files uploaded using FileField will go.
Absolute filesystem path to the directory that will hold user-uploaded files.
STATIC_ROOT is the folder where static files will be stored after using manage.py collectstatic
The absolute path to the directory where collectstatic will collect static files for deployment.
If the staticfiles contrib app is enabled (default) the collectstatic management command will collect static files into this directory. See the howto on managing static files for more details about usage.
STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.
This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.
In your settings, you should have:
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# Make a tuple of strings instead of a string
STATICFILES_DIRS = ("/home/user/project/django1/top/listing/static", )
...where:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
as defined in the default Django settings.py now.
Difference between STATICFILES_DIRS and STATIC_ROOT
The STATICFILES_DIRS can contain other directories (not necessarily app directories) with static files and these static files will be collected into your STATIC_ROOT when you run collectstatic. These static files will then be served by your web server and they will be served from your STATIC_ROOT.
If you have files currently in your STATIC_ROOT that you wish to serve then you need to move these to a different directory and put that other directory in STATICFILES_DIRS. Your STATIC_ROOT directory should be empty and all static files should be collected into that directory.
MEDIA_ROOT where media files ,all uploaded files goes.
Example : Images, Files
class Media:
js = ('/admin/custom.js', )
but it is not working. Throwing 404 not found error.
The 404 error is in part because of the leading slash in the file path.
I'm using AppFog PaaS system for a few days, and I love it, It's probably the best PaaS system that I've tested (I've used other 3 ones previously), but didn't find information about how to serve static content with the Web server in frontend (Apache https or nginx) I'm not sure what server is being used.
My app is a Python WSGI with CherryPy and works perfectly in AppFog but I don't wan't CherryPy to serve static content, I think that Apache httpd or nginx is a better option for that.
With Ryan's support, I'm finally able to load static files! Here are the steps:
Created a 'static' directory in the project root - here all static files will be collected running the collectstatic command.
Edit the settings.py file:
STATIC_ROOT = os.path.join( os.path.abspath( os.path.dirname(file) ), '../static' ) # May change depending on where your settings.py file is!
STATIC_URL = '/static/'
Add following line in urlpatterns variable in urls.py file:
url(r'^static/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT} ) ,
Finally, run collectstatic command in your local machine. This will copy all static files from the apps you are using:
python manage.py collectstatic
That's it. Push in AF :)
Downside: Need to run collectstatic every time we have a new static file...
Edit your nginx.conf file. In the server section enter...
# serve static files
location ~ ^/(images|javascript|css)/ {
root /var/www/html/appname;
}
images, javascript and css would be folders in your document root folder. Update all your urls accordingly.