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.
Related
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 :).
I have recently set up our project to serve static and media files from Amazon S3. This in turn has made our project serve all content from S3 even when working locally.
Our static settings are set to the following to work with S3:
STATIC_ROOT = "/%s/" % STATIC_S3_PATH
STATIC_URL = '//s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME
And in the URLs conf file we have added the following to match the Django documentation:
if settings.DEBUG:
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'^static/(?P<path>.*)$', 'serve'),
url(r'^media/(?P<path>.*)$', 'serve'),
)
Obviously these URL patterns will not work because we are serving files on "//s3.ama...". I thought in my wisdom that I could then write a piece of regex to get around the problem and tried replacing:
url(r'^static/(?P<path>.*)$', 'serve'),
with:
url(r'//s3.amazonaws.com/%s/static/(?P<path>.*)$' % settings.AWS_STORAGE_BUCKET_NAME, 'serve'),
This didn't work either. So to finally get around the problem I added a conditional statement in the settings file to decided where to serve static files from:
if DEBUG:
STATIC_URL = '/static/'
else:
STATIC_URL = '//s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME
What do people think of this solution? I'm not really happy with it going forwards. What are my alternatives?
The conditional in the settings is a good solution.
Another option is to use a separate settings file for local settings.
I am from PHP background and want to give path to
STATICFILES_DIRS
in settings.py and in windows I understand that I will need to give full path like:
D:/path/to/folder/project/static
I want to know that is there a way to give some path like "/static/" or can we give path like dirname(__FILE__) in PHP?
So that my path is not hardcoded. Also why it is physical path as webserver normally don't follow physical path for loading CSS files as it use http path? So why it is this way(physical path) in django? Can some one please explain.
thanks for everyone's effort in advance.
In my settings.py files, I always do
import os
ROOT_PATH = os.path.dirname(__file__)
Then you can do
STATICFILES_DIRS = [os.path.join(ROOT_PATH, 'static')]
The reason that STATICFILES_DIRS wants a filesystem path is that it needs to know where the files live in the operating system (so things like manage.py collectstatic are possible). The STATIC_URL setting is for webserver paths, and that's what it uses to show to the user in the admin or the {% static %} tag or whatever. STATICFILES_DIRS is server-side only and never shows up in any rendered templates or anything.
Find the settings.py file in the project,
Put:
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'))
Change to:
STATICFILES_DIRS=[(os.path.join(BASE_DIR,'static'))]
Answer on your question is wrong. If you do like this, you'll get the next error:
ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
My decision is add to top of settings.py file the next function:
import os
def look_folder_tree(root):
result = ()
for dir_name, sub_dirs, file_names in os.walk(root):
for sub_dir_name in sub_dirs:
result += (os.path.join(dir_name, sub_dir_name),)
return result
# Django settings for project.
PROJECT_DIR = os.path.dirname(__file__)
and call look_folder_tree function at:
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = look_folder_tree(STATIC_ROOT)
My decision is allow to add all sub folders inside static directory.
In settings.py :
Import os (already done when you create a django project)
import os
You can just use STATICFILES_DIRS as a tuple, mind the trailing comma.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Or you can use the STATICFILES_DIRS as a list data-type, comma at the end is not required here:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Change this:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
To This:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Add a comma at last as,
ERRORS:
?: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list.
HINT: Perhaps you forgot a trailing comma?
your syntax is correct, I think you forget of importing os at the first line of code as import os.
If you are using newer versions of Django i.e Django 3.1, and your BASE_DIR is like this ...
BASE_DIR = Path(__file__).resolve().parent.parent
Then do this :-
STATICFILES_DIRS =[BASE_DIR / 'my_app/static',]
I've been messing around with the new collectstatic command and have got it working for my normal pages. That is to say, I am able to load my css at this location http://localhost:8000/static/css/main.css. However, the css for my django admin doesn't seem to be showing up.
When I navigate to the admin css location at http://localhost:8000/static/admin/css/base.css, I'm getting a 404 page not found with the following error: /home/nai/GitProjects/cats/django-trunk/django/contrib/admin/media/css/base.css" does not exist. Looking in django-trunk, I never had the /home/nai/GitProjects/cats/django-trunk/django/contrib/admin/media/ folder to begin with.
Is that weird?
In any case, in my static folder, there is an admin folder with the accompanying css, img and js folders which was created when I ran collectstatic and the url of the base.css seems to be pointing to that location.
This is happening on my django development server. Here are some snippets to aid in the bug hunt:
urls
33 # In order for Dev Server to serve media files for the frontend site.
34 urlpatterns += staticfiles_urlpatterns()
35
36 try:
37 if settings.DEBUG: # defined in manage.py when the first arg is "runserver"
38 urlpatterns += patterns('',
39 (r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
40 (r'^media-admin/(?P<path>.*)$', 'django.views.static.serve',{'document_root': os.path.join(settings.MEDIA_ROOT, '..', settings.ADMIN_MEDIA_PREFIX)}),
41 )
42 except NameError:
43 pass
I think it might be something to do with line 40 in my URLS file but changing media-admin to static/admin didnt help.
settings
58 ADMIN_MEDIA_PREFIX = '/static/admin'
69 STATIC_ROOT = os.path.join(os.path.abspath(os.path.join(PROJECT_ROOT, '..', MEDIA_DIR, 'static')), '')
70
71 # URL prefix for static files.
72 # Example: "http://media.lawrence.com/static/"
73 STATIC_URL = '/static/'
74
75 # Additional locations of static files. Global files are stored in here
76 STATICFILES_DIRS = (
77 os.path.join(os.path.abspath(os.path.join(PROJECT_ROOT, '..', 'proj_public', 'static', 'proj')), ''),
78 )
79
Django recommends that you deploy static files with a web server other than wsgi.
In settings.py, set:
STATIC_ROOT = 'static'
Run python manage.py collectstatic, which will copy the Django admin static files to /path/to/project/static/
Configure your static file server. If you use Nginx, you could add this config:
location /static/ {
alias /path/to/project/static/;
expires modified +1w;
}
Reload your web server
You should now have access to the static files.
In Django 1.4 ADMIN_MEDIA_PREFIX is deprecated. Here are the steps I followed to catch up with these somewhat recent Django changes:
in settings.py, add django.contrib.staticfiles to INSTALLED_APPS
in settings.py define STATIC_URL — the staticfiles app won't run without it. While using runserver they'll get handled magically, but when you deploy, this needs to be a location where those resources can be fetched by a browser.
I think that's all there was to it.
I'm using Django 1.4.3
What did NOT work for me:
No matter how much I edited ADMIN_MEDIA_PREFIX in settings.py I noticed no change in the HTML generated for the Django Admin pages. It always says /media/admin/base.css when I view the source.
What DID work for me.
Copied the 'admin' folder from /django/contrib/admin/static/ and pasted it into my projects 'media' folder
Now it works great.
It seems dumb, but I actually had this exact issue and the solution was to set DEBUG=False to DEBUG=True on my local dev environment. When debug is set to False, it thinks it's in a production environment which relies on a place to put static files, such as /var/www/html/static, whereas the debug set to True just uses the local directory.
Also make sure that AppDirectoriesFinder is not commented, happens when you're trying to customize your own app structure. Unfortunatelly it's pointless to seek such information in official docs.
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
just change one thing in settings.py
DEBUG = False # not working if you are not serve your static files for production.
just change
DEBUG = True
You need a trailing slash in your ADMIN_MEDIA_PREFIX setting.
Change to:
ADMIN_MEDIA_PREFIX = '/static/admin/'
I'm using chef to auto-build my django server on an AWS Ubuntu server. This post helped, but what I wound up doing was to add the directory to the package admin static pages in a local_setings.py:
https://github.com/jaycrossler/geoq-chef-repo/blob/master/cookbooks/geoq/templates/default/local_settings.py.erb#L16
(added to local_settings.py or to settings.py):
STATICFILES_DIRS = ('<%= node['geoq']['virtualenv']['location'] %>/local/lib/python2.7/site-packages/django/contrib/admin/static/',)
This resulted in local_settings.py having:
STATICFILES_DIRS = ('/var/lib/geoq/local/lib/python2.7/site-packages/django/contrib/admin/static/',)
Note, that if you have other items already in your STATICFILES_DIRS, you might want to append to the list, rather than overwriting it.
in my project, the solution is in settings.py, set:
DEBUG = False # debug false mod not working css
One solution might be to add your local IP to the ALLOWED_HOSTS list in settings.py
e.g.
CURRENT_IP = '192.168.0.123'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '0.0.0.0', CURRENT_IP]
you need
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I don't know how it was resolved, but I took these steps when I encountered the same problem. I simply add these line in settings.py.
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','compressor.finders.CompressorFinder', )
i hope this will help you all.
In settings.py
Don't use tuple for the
STATICFILES_DIRS =(
os.path.join(BASE_DIR, 'static'),
)
you should use list,like this
STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'static'),
]
my settings.py file
MEDIA_ROOT = '/home/path/to/htdocs/mysite/public/media/'
MEDIA_URL = '/site_media/'
ADMIN_MEDIA_PREFIX = '/media/'
in site_media i have my images and CSS
...href="{{ MEDIA_URL }}/style.css" ... (with {{ MEDIA_URL }}style.css is this same)
after render it look like this
href="/site_media/style.css"
but at http://example.com/site_media/style.css there is Unhandled Exception (i thing no url mapped in urls.py)
everything is work fine in DEBUG mode because i have this in urls.py
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'media')}),
(r'^site_media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'site_media')}),
)
but what I need to do when DEBUG = False
what is happening is that in DEBUG mode django serves your style.css file. You tell it to do that with this line
(r'^site_media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'site_media')}),
)
But this line does not go into the urlpatterns variable when debug is false. To test that try to access localhost:8000/site_media/style.css when debug is true (should work) and when it is false (will give a 404 error).
You could just leave out the
if settings.DEBUG:
part, but that means that django would still serve static files and that is not recommended in production for performance reasons.
In a production setup you should use a different webserver to serve your static files. I have had good experiences with nginx running in front of apache.
This is an excellent tutorial which shows you how to create such a setup:
http://www.ventanazul.com/webzine/tutorials/django-deployment-guide-ubuntu
Be prepared though that creating a production setup is not quite as painless as just typing python manage.py runserver. I have also heard good things about using nginx together with gunicorn and that that makes setting up a production server much simpler, but have no experience with it myself.
You need to serve them somehow yourself.
http://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-from-a-dedicated-server
In production, use something like Apache or Nginx to serve your static files.
Basically, you map a URL (in your case /site_media/) in the server to a folder on your server (like wherever your media directory is now) and you're done. All requests to /site_media/ now don't go to your app but go searching the directory for static files to serve.
Implementation depends on which server setup you go for.