Running Django 1.8.4
Static files have been working on local. I've uploaded the project to a VPS and everything is working except the static files.
Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
Example CSS files reference in template
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
sudo nano /etc/nginx/sites-available/soundshelter
server {
server_name MYSERVER;
access_log off;
location /static/ {
alias /opt/soundshelter/soundshelter/static/; #this is the valid location
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
Urls.py
from django.conf.urls import patterns, url,include
from soundshelterapp import views
urlpatterns = patterns('soundshelterapp.views',
url(r'^$', views.home, name='home'),
url(r'^release/(?P<release_id>\d+)$', views.release, name='release'),
url(r'^genre/(.*)$', views.genre, name='genre'),
url(r'^label/(.*)$', views.label, name='label_no_country'),
url(r'^artist/(.*)$', views.artist, name='all_artists'),
url(r'^recommendations/(.*)$', views.recommendations, name='user'),
url(r'^personalised$', views.personalised, name='name'),
url(r'^social/', include('social.apps.django_app.urls', namespace='social')),
url(r'^login/$', 'login',name='login'),
url(r'^logout/$', 'logout',name='logout'),
url(r'^save_release/$', views.save_release, name='save_release'),
url(r'^unsave_release/$', views.unsave_release, name ='unsave_release'),
)
To avoid hardcoding, you can set STATIC_ROOT this way:
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
So your static files for production will be in a directory near your project's folder. Moreover you can do the same stuff with MEDIA_ROOT.
MEDIA_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "media")
Thanks Hedde van der Heide for the solution
Setting STATIC_ROOT to the actual location of the files worked
e.g.
STATIC_ROOT = "/var/www/example.com/static/"
https://docs.djangoproject.com/en/1.8/howto/static-files/#deployment
Do render a static file in your live website, you have to add the below code in your setting file.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collect static to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
Also add this in your INSTALLED APPS,
INSTALLED_APPS =
['django.contrib.staticfiles',]
Related
django settings:
CKEDITOR_BROWSE_SHOW_DIRS = True
CKEDITOR_RESTRICT_BY_USER = True
CKEDITOR_RESTRICT_BY_DATE = False
CKEDITOR_UPLOAD_PATH = 'uploads/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT = os.path.join(BASE_DIR, "attachments")
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'), )
STATIC_URL = f"{FORCE_SCRIPT_NAME}/backend/static/"
MEDIA_URL = f"{FORCE_SCRIPT_NAME}/backend/attachments/"
urls:
urlpatterns = [
path('admin/filebrowser/', site.urls),
path("grappelli/", include("grappelli.urls")),
path('admin/', admin.site.urls),
path("api/", include(api_urlpatterns)),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT,
show_indexes=settings.DEBUG)
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT,
show_indexes=settings.DEBUG)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path("__debug__/", include(debug_toolbar.urls)),
] + urlpatterns
nginx:
location /project_name/ {
set $service project_name;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://$service;
client_max_body_size 16m;
}
In dev all works, upload and browse, but in prod with not (AH00128: File does not exist: /var/www/html/project_name/ckeditor/upload). I try add alias/root to nginx config, change ckeditor path to re_path(r'^ckeditor/', include('ckeditor_uploader.urls')) and still nothing( Not only upload, browse too not working
For example filebrowse works, but not ckeditor. I dont know a reason why.
Add in projects apache settings in service.conf -> WSGIScriptAliasMatch ckeditor alias:
WSGIScriptAliasMatch ^/${SERVICE}/((admin|api|grappelli|ckeditor)/.*)$ /${SERVICE}/backend/${PROJECT}/wsgi.py/$1
Now works.
The user interface is working well, and all CSS styling and static files are served correctly, but the admin interface is missing CSS styling. I looked at similar posts but in those posts people had the issue with both the user and the admin interface. My issue is only with the admin interface.
Please see my static file settings below from settings.py:
STATIC_URL = '/static/'
#Location of static files
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And this is my nginx configuration:
server {
listen 80;
server_name MY_SERVER_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/MYUSERNAME/myproject;
}
location /media/ {
root /home/MYUSERNAME/myproject;
}
I already executed python manage.py collectstatic on the server and got this message:
0 static files copied to '/home/MYUSERNAME/myproject/staticfiles', 255 unmodified.
I restarted nginx after that and also tried emptying my browser cache, but the issue persisted.
More info as requested by #Omar Siddiqui.
Using Django 3.2
My mysite/urls.py contains:
from django.contrib import admin
from django.urls import path, include
# Imports to configure media files for summernote editor
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('qa.urls')),
path('summernote/', include('django_summernote.urls')),
path('chatbot/', include('chatbot.urls')),
]
# Enable media files for summernote editor
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Could you please try below steps and let me know if it's working or not?
Apply below changes in settings.py file:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Remove below line from your settings.py:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
Execute below command in production:
python manage.py collectstatic
Update nginx file like below one:
server {
listen 80;
server_name MY_SERVER_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
autoindex on;
autoindex_exact_size off;
root /home/MYUSERNAME/myproject;
}
location /media/ {
autoindex on;
autoindex_exact_size off;
root /home/MYUSERNAME/myproject;
}
}
Explanations:
STATIC_ROOT is the folder where static files will be stored after
using python manage.py collectstatic
STATICFILES_DIRS is the list of folders where django will search for additional static files aside from the static folder of each app installed.
In this case our concern was Admin related CSS files that why we use STATIC_ROOT instead of STATICFILES_DIRS
Try changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then re-run python manage.py collectstatic. This has worked in the past for some people
Try passing an alias to the static location in nginx, like so:
location /static/ {
alias /home/MYUSERNAME/myproject/staticfiles/
}
Don't forget to restart nginx afterwards.
I have wondered around lot of other stackoverflow issues to see if there is a solution but i couldn't work around it. So here is the issue:
Nginx.conf
location /media/ {
alias /root/server/media/;
}
location /static/ {
alias /root/server/static/;
}
urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static/'),)
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
wsgi.py
application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'static'))
application = WhiteNoise(application, root=os.path.join(BASE_DIR, 'media'))
I have set everything as necessary, i check the directory (root/server/media) and images are there. But when i enter the link : $serverlink/media/images/1.png , it gives me 404 (Not found) error. Does anybody know why?
Update:
Can you try removing the trailing slash after media?
location /media { alias /root/server/media; }
I am testing my django app in production mode (debug=false) using nginx, gunicorn, postgresql.
Though I am able to render static files, I am unable to access files stored in 'media' folder.
In my settings.py following are the variables set:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# also tried another combination: MEDIA_ROOT = 'media'
Also in urls.py the MEDIA_ROOT settings are as follows:
urlpatterns = [
path('admin/', admin.site.urls),
path('venter/', include('appname.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in my /etc/nginx/sites-available/ file I have the following settings:
server {
listen 80;
server_name website.com www.website.com ;
location = /favicon.ico { access_log off; log_not_found off; }
location /static {
root /home/a/btawebsite;
}
location /media/ {
root /home/a/btawebsite;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/a/myproject.sock;
}
}
However while rendering the xlsx file stored in my django database as follows it throws me NOT found error.
{{file.output_file.url}}
I have tried every combination of configurations required for rendering MEDIA files but unable to achieve the outcome.
Thanks.
UPDATE: following changes to be made in settings.py
MEDIA_URL = '/'
MEDIA_ROOT = 'media'
If everything in django settings is properly configured you just need to add the following in the nginx conf:
location /media {
alias /home/user/django_app/media; #(locaion of your media folder)
}
In your settings.py write like this
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # root for media files
MEDIA_URL = "/media/"
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
FORCE_SERVE_STATIC = True
DEBUG=False
In your urls.py change like this
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
elif getattr(settings, 'FORCE_SERVE_STATIC', False):
settings.DEBUG = True
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(
settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.DEBUG = False
In your nginx.conf file change the root to your media folder
location /media/ {
root /home/nazmi/workspace/portal/media/ (url for your media folder);
}
First of all, remove the +static() from your urls.py. That's not correct for production, only for development.
In your nginx configuration, location = /media/ only applies for exact
matches, not locations starting with /media/. Remove the =.
I having difficulty serving static files with Django 1.10, uWSGI and Nginx.
I have an index.html file, which contains CDN's.
The Django documentation, which is here says to "transfer the static files to the storage provider or CDN." What does that mean, "transfer to the CDN"? Isn't the CDN where you get files from?
settings.py contains,
STATIC_URL = '/static/'
STATIC_ROOT = 'nonAppBoundStaticDirectory'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Running
$ python manage.py collectstatic
does this place all CDN's in my directory 'nonAppBoundStaticDirectory'?
If so then how do i use that in the template?
Excerpt from index.html
<!-- Bootstrap -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
Excerpy from /etc/nginx/nginx.conf
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name example.com; # substitute your machine's IP address or FQDN
charset utf-8;
#Max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias /home/ofey/djangoForum/fileuploader/uploaded_files; # your Django project's media files
}
location /static {
alias /home/ofey/djangoForum/noAppBoundStaticDirectory; # your Django project's static files
}
........
Thanks,
It might be just a spelling mistake. In your settings.py you have an extra n in the directory name.
STATIC_ROOT = 'nonAppBoundStaticDirectory'
In your nginx config, you have a different spelling.
location /static {
alias /home/ofey/djangoForum/noAppBoundStaticDirectory;
Make sure that the path point to the exact same directory. It's can be a good idea to use absolute paths in both cases.
Working in development server
If you are working in development server- remove STATIC_ROOT from settings.py. Your settings.py should now look like this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Production
If you are working in production- remove STATICFILES_DIRS from settings.py. Your settings.py should now look like this:
STATIC_URL = '/static/'
STATIC_ROOT = 'nonAppBoundStaticDirectory'
And don't forget to run:
python manage.py collectstatic