Serving Django Static Content based on DEBUG status - django

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.

Related

having problem with django static file set up

I can only and only set the static files in Django with this code
In Installed Apps in settings.py
'....',
'staticfiles',
'....
In end of settings.py
STATIC_URL = '/staic/'
STATICFILE_DIRS = [
os.path.join(BASE_DIR, '/static')
]
And It worked. At My First Time, I also tried this
In urls.py
#this way
urlpatterns = [
...,
...,
.....,
] + static(STATIC_URL, document_root=STATIC_ROOT)
#or
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
At the first time it worked but after that project this way didn't work
I viewed thousands of websites.
I did all the thing in the code like the youtube tutorial
But the second code didn't work anymore. But I cannot use the development server in production. But the first code (which works for me) requires a development server.
If Anyone knows please (if possible) give me the example code to try it, the possible answer, and all the websites where I can know more. It would be helpful.
Thanks Very Much
in settings.py write this code
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Is not a metter of URLs in your application.
As you say, django development server is not suitable for production environment.
You need a reverse proxy like Apache or Nginx in order to be able to serve the static files to your application and WSGI HTTP Server to run your application like gunicorn
Here is a link with a very nice guide on how to setup gunicorn and nginx for django production environment.
DigitalOcean
Vexxhost
Medium

How to configure Django's "staticfiles" app to list directory contents?

I'm using Django's built-in web server, in DEBUG mode.
This is part of my settings.py:
STATIC_ROOT = '/home/user/static_root'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/abs/path/to/static/dir',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
If I access http://localhost:8000/static/png/, I would expect to see a list of files available in /abs/path/to/static/dir/png. Instead I get a 404 error "Directory indexes are not allowed here."
Now if I access the files directly, e.g. http://localhost:8000/static/png/test.png, it works.
I've already checked some answers (here) without success.
So, does anyone know how to configure Django such that the staticfiles app lists directory contents?
Just for completeness since it might help others, this is what I did to solve the problem.
Following #Hedde's answer, I went to use show_indexes:
settings.py
Kept all the configuration the same (i.e. all the STATIC* variables)
Removed 'django.contrib.staticfiles' from INSTALLED_APPS
The problem is that I cannot specify the show_indexes parameter using Django's "built-in" method for static file configuration (via settings.py). By having 'django.contrib.staticfiles' in INSTALLED_APPS, Django would create the static file handler with show_indexes = False, ignoring my urlpatterns.
urls.py
Added the following to urlpatterns:
url(regex = r'^%s(?P<path>.*)$' % settings.STATIC_URL[1:],
view = 'django.views.static.serve',
kwargs = {'document_root': '/abs/path/to/static/dir',
'show_indexes' : True})
'show_indexes': True
As per the documentation
From https://docs.djangoproject.com/en/1.5/ref/views/#django.views.static.serve ...
static.serve(request, path, document_root, show_indexes=True)
Those files are not meant to be served by django. Show indexes is a configuration parameter of apache/nginx.
In production, with nginx, just add to the static serving part :
location ^~ /static/ {
autoindex on;
root /var/www/static_dir;
if ($query_string) {
expires max;
}
}
For dev environnement, Hedde's answer is indeed the good answer, but the display may not be the exact same than the one offered by your HTTP server. Don't rely on it's look&feel.

Django static files stop working if turn on debug

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.

Django Admin CSS missing

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'),
]

Django MEDIA_URL again ... Unhandle

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.