STATIC_ROOT in Django on Server - django

I'm 2hours stuck in a issue about STATIC_URL and STATIC_ROOT when I try to make run the webapp on my server at webfactional.
when I load the webpage all the requests works well, except by the fact that any link with {{ STATIC_URL}} is working or loading.
So a common error that appears on firebug is:
GET http://mydomain/static/extras/h5bp/js/libs/modernizr-2.5.3.min.js 500 (Internal Server Error)
My setup is:
urls.py
I did nothing, and there's nothing about static files.
settings.py
DEBUG = False
STATIC_ROOT = '/home/mydomain/webapps/static_app/'
STATIC_URL = 'http://mydomain/static/'
STATICFILES_DIRS = ()
views.py
view example
#csrf_exempt
def IndexView(request):
try:
request.user.is_authenticated()
except AttributeError:
return render_to_response('index.html',
{'request': request,},
context_instance=RequestContext(request))
return render_to_response('index.html',
{'request': request, 'profile' : request.user},
context_instance=RequestContext(request))
index.html
a part of code not found
<script src="{{ STATIC_URL }}extras/h5bp/js/libs/modernizr-2.5.3.min.js"></script>
well, I follow all the points of:
https://docs.djangoproject.com/en/1.4/howto/static-files/
and this another one:
http://docs.webfaction.com/software/django/getting-started.html
I'm using the correct installed apps, middlewares, template_contexts.
If I'm missing something please help me to figure out.
Thanks in advance!
--edit
I have to say, if I just change the DEBUG = True will works fine.
because on urls.py I have this piece of code:
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)/$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))

2 things must happen on a production environent that is not needed in the development environment.
You must run manage.py collectstatic -- this collects all static files into your STATIC_ROOT directory.
You must serve your STATIC_ROOT directory at the STATIC_URL url. How exactly depends on your production setup. This is not even django related; all that matters is that STATIC_ROOT contents are available at STATIC_URL.
Let's say you're using Apache, you'd alias a URL to a directory.
Alias /static/ /path/to/my/static_root/
If you're using nginx, it would be something like
location = /static/ {
alias /path/to/my/static_root/;
}
I just realized you're using webfaction, in which case you set up a static application which literally just serves files at the targeted directories at the URL you define. I'm trying to remember my webfaction login to see the exact procedure, but it shouldn't be difficult to figure out.
Update:
Logged into webfaction; you can create an application that is a symlink. Easy!
Create a symbolic link app that serves /YOUR_STATIC_URL/ and point it to /YOUR_STATIC_ROOT/. Done!

Related

Prod server serving files only when debug turned on- Django

I am trying to serve dynamically created files on my Django server.
The code works fine and serves the image file from media folder on my local server.
It also works and serves the image file in Production server but only when I set debug to True in Prod server.
But when I set debug to False in Prod Server, I get a file not found error (in console):
GET http://thesitename/media/imgs/img.png 404 (Not Found)
The server serves the files from the /static folder, but does not serve the files from /media folder.
my settings.py looks like this:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "frontend/media/")
urls.py looks like this:
app_name = 'frontend'
urlpatterns = [ ###urls###
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Views.py looks like this:
def template_page(request, loation, par, date):
### generating image using pil here ###
pil_image.save("frontend/media/imgs/img.png”)
path_to_image_passing_to_template = “/media/imgs/img.png”
params = {
'path_to_image_passing_to_template' : path_to_image_passing_to_template
}
return render(request, 'frontend/template_page.html', params)
html looks like this:
<img src="{{path_to_image_passing_to_template}}" />
and file structure is like this:
/backend
urls.py
views.py
/frontend
/static
/media
/imgs
/templates
/frontend
urls.py
views.py
/thesite
settings.py
urls.py
wsgi.py
/static
I don't understand why it should work with debugging turned on in prod server and not otherwise!!!
I have looked at several questions but did not find any query close to this kind of issue. I took some help while writing working out the dynamic media files code from this answer earlier but am stuck right now.
Confirm that you have 'os.environ' module loaded...try executing the
code below on the production server.
import os
print(os.environ.get('MEDIA_ROOT'))
Make sure it shows the expected path.
then ensure that your 'urls.py' and 'Views.py' have 'import os' line appearing at the top of the file. Good Luck!

Django: Static files missing when rendering template

I am using django 1.3 and trying to deploy a django project (client sent) on my dev machine (ubuntu 12.04). The problem is regarding the static files. My directory structure is as follows:
project_name
media
static
css
img
js
settings.py
Here is my settings.py:
ROOT = '/home/user/project_name'
MEDIA_ROOT = '%s/media/' % ROOT
MEDIA_URL = '/media/'
STATIC_ROOT = '%s/static/' % ROOT
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
My site is perfectly deployed but the css, js and imgs are missing. Same is the case for the admin interface. When I use the link http://mysite.com/static/js/some.js it gives a 404.
Help would be appreciated and up-voting an answer is custom.
I think you need to run ./manage.py collectstatic :)
You don't mention configuring your web server to actually serve the static files. You need to point it at the directory that collectstatic put them into.
did you run python manage.py collectstatic ? see here
be careful that in production you should place the static file in a static server. There should be something in the guidelines.
And a little offtopic..
It will be better, to use:
MEDIA_ROOT = os.path.join(os.path.dirname(file),'media').replace('\','/')
STATIC_ROOT = os.path.join(os.path.dirname(file),'static').replace('\','/')
and in main urls.py at development, django webserver only:
urlpatterns = patterns('',
(r'^media/(?P.*)','django.views.static.serve',{'document_root': os.path.join(os.path.dirname(file),'media').replace('\','/') }),
(r'^static/(?P.*)','django.views.static.serve',{'document_root': os.path.join(os.path.dirname(file),'static').replace('\','/')}),
In this way, u dont need collectstatic, ull need it at production server, where u will use nginx or something other to server your static

Adding expire header for Django static files on Heroku

I'm trying to optimize my webpage and am having trouble setting expiration date headers on my static files.
I am running django-1.5, python-2.7.3.
Here's my cache settings in settings.pyso far:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': os.path.join(PROJECT_ROOT, 'cache/'),
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 5 * 60
CACHE_MIDDLEWARE_KEY_PREFIX = ''
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
...
'django.middleware.cache.FetchFromCacheMiddleware',
)
And my static file settings in settings.py:
import os.path
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(PROJECT_DIR, '..'))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles/')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
The closest advice I've found was here, but I'm unable to modify the .htaccess files on Heroku.
Any help is greatly appreciated. Thanks!
The django staticfiles app does not provide out of the box support for custom headers. You'll have to hack together your own view to serve up the files and add custom headers to the HttpResponse.
But You should not be serving your static files using Django. This is a terrible idea.
Django is single-threaded, and blocking. So every time you're serving a user a static file, you're literally serving nothing else (including your application code, which is what Django is there for).
Django's staticviews file is insecure, and unstable. The documentation specifically says not to use it in production. So do not use it in production. Ever.
In production you shouldn't serve static files with Django. See the warning boxes on this page: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#static-file-development-view
In development, Django's contrib.staticfiles app automatically serves staticfiles for you by overwriting the runserver command. This way you can't control the way it serves the static files.
You can prevent the staticfiles app from serving the static files by adding the --nostatic option to the runserver command:
./manage.py runserver --nostatic
Then you can write an url config to manually serve the static files with headers you want:
from functools import wraps
from django.conf import settings
from django.contrib.staticfiles.views import serve as serve_static
from django.conf.urls import patterns, url
urlpatterns = patterns('', )
if settings.DEBUG:
def custom_headers(view_func):
#wraps(view_func)
def wrapper(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
response['Custom-header'] = 'Awesome'
response['Another-header'] = 'Bad ass'
return response
return wrapper
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', custom_headers(serve_static)),
)
If you want your manage.py to have the --nostatic option on by default, you can put this in your manage.py:
if '--nostatic' not in sys.argv:
sys.argv.append('--nostatic')
I think since you are hosting your project on heroku , the generally accepted practice seems to be using S3 for serving static files.
Have a look at this question :
Proper way to handle static files and templates for Django on Heroku
I am not too sure about this but I am sure you should be able to change headers while serving files from S3 atleast this SO question seems to suggest that way
Is it possible to change headers on an S3 object without downloading the entire object?
Hope this helps

How to use django-cumulus for serving Static files?

I'm trying to use django-cumulus for serving files off Rackspace CloudFiles. I'm currently only trying it on my local dev server, using Django 1.4.2.
I can use cumulus's syncstatic management command to upload all my static assets successfully, but I can't seem to display them on my site with the same settings.
If my relevant settings are:
STATIC_URL = '/static/'
CUMULUS = {
'USERNAME': 'myusername',
'API_KEY': 'myapikey',
'CONTAINER': 'mycontainername',
'STATIC_CONTAINER': 'mycontainername',
}
DEFAULT_FILE_STORAGE = 'cumulus.storage.CloudFilesStorage'
STATICFILES_STORAGE = 'cumulus.storage.CloudFilesStaticStorage'
then when I run syncstatic all my apps' static files are uploaded into /mycontainername/static/, as I'd expect. But when I load a page in admin it ignores STATIC_URL and tries to serve assets from URLs like http://uniquekey....r82.cf2.rackcdn.com/path/to/file.css rather than http://uniquekey....r82.cf2.rackcdn.com/static/path/to/file.css.
Also, I can't see how to have my public (non-admin) pages use the static files on CloudFiles, rather than serving them from a local /static/ directory.
Have I missed some crucial setting, or am I doing something else wrong?
I had the same problem. What i did was to
git clone https://github.com/richleland/django-cumulus.git
edit context_processors.py
from django.conf import settings
from cumulus.storage import CloudFilesStorage
def cdn_url(request):
"""
A context processor to expose the full cdn url in templates.
"""
cloudfiles_storage = CloudFilesStorage()
static_url = '/'
container_url = cloudfiles_storage._get_container_url()
cdn_url = container_url + static_url
print {'CDN_URL': cdn_url}
return {'CDN_URL': cdn_url}
Once you are done, install it with sudo python setup.py install
Do note that context_processors.py from django cumulus is actually quite slow

Django Static Files CSS

How can I view my static css files? I've set my STATIC_ROOT, and am using python manage.py runserver.
In my development environment, according the docs, I only need to place my static files (in this case, /static/css/typography.css) in my STATIC_ROOT, and python manage.py runserver will automatic create the views necessary to access it if I have DEBUG = True.
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static")
I've also tried manually adding the views in URLConf, which won't display the css file either:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
In my template, the {{ STATIC_URL }} gets to the correct address (/static/css/typography.css), but it will not serve the file when I try to access it:
<link href="{{ STATIC_URL }}css/typography.css" rel="stylesheet" type="text/css">
Notes: The other Django related static files questions on StackOverflow are over two years old. Django version 1.3b1 differentiates STATIC (static files, such as css and images) and MEDIA (user-uploaded file).
Besides. all the tries mentioned above, you must also make sure that your template is receiving the RequestContext when called from the view.
http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
This link gives various ways of doing the same and you could choose any one. :) Also, the TEMPLATE_CONTEXT_PROCESSORS must be added to settings.py for this to take effect.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.processor.foos",
)
Note: STATIC_ROOT is the place where all your static files are stored by Django after collecting them from STATICFILES_DIRS.
Runserver will pick them up from the path mentioned in STATIC_ROOT, so STATIC_URL should point to the same location as STATIC_ROOT.
Answered here: Django staticfiles app help
I was putting my files in STATIC_ROOT, so adding this works:
STATICFILES_DIRS = (STATIC_ROOT,)
In development:
#settings.py have this by default
STATIC_URL = '/static/'
This means when you want to use static files, django will look for them in folder 'static' in your app directory. So you need to create folder 'static' in every your app and put inside your static files.
In production:
1. Make place to hold static files from all app's
STATIC_ROOT = "/var/www/example.com/static/"
2. Run python manage.py collectstatic to collect static files from all app's in STATIC_ROOT folder.
3. In settings.py change DEBUG=False and ALLOWED_HOSTS = ['yourhostadress'].
4. Point your webserver to STATIC_ROOT folder (eg. for Apache2.4):
Alias /static/ /path/to/mysite.com/static/
<Directory /path/to/mysite.com/static>
Require all granted
</Directory>
After this setup, your django project should be able to run (using mod_wsgi) and use static files on Apache web server.