Static file cannot be found in Django view - django

I am having an issue with static files in the development server on Django 1.5.4. I am not sure if it is the same problem on the actual production server (running Apache), as I found a solution for that which works at the moment (simply hard coding the full URL - I know it's bad, but it gets the job done).
I am using Reportlab to create a PDF file for my project, and I need to include a picture on that. I followed the answer in a different post:
from django.templatetags.static import static
url = static('x.jpg')
Unfortunately, the answer I get from the server is an IO Error: 'Cannot open resource "localhost:8000/static/images/x.jpg"', even though a copy and paste of that into the URL bar clearly shows me that the picture is exactly there.
My settings regarding static files are the following, and they do work for everything else (CSS, Javascript, etc):
ROOT_PROJECT = os.path.join(os.path.split(__file__)[0], "..")
STATIC_ROOT = os.path.join(ROOT_PROJECT, 'static')
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Thanks for your help!

Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
There are usually a couple of ways to store static files.
One way is to create a static folder inside your app folder and store the files there. You can check that here:
Is to create a folder and store your static files which are not for any particular app.
From the django documentation:
Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.
For example:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
)
If you are into production then check production deployment for more details!

Related

Using both the project level and the app level static files in django

I have some static files that will remain common through all the application and I also have some static files that are specific to some particular apps only. Now in one of my apps, i want to use both the project level and the app level static files but that doesn't seem to work.
Following code section is from settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "homepage","static"),
os.path.join(BASE_DIR, "landing_page","static"),
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I have used python manage.py collectstatic
and it returns with a warning which goes like Found another file with the destination path 'homepage\css\style.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure
every static file has a unique path.
Despite the above warning, I still get both the project level and the app level static files in the staticfiles folder in my root directory. When I use it in a template, the project level static file gets loaded while the app level static file (which is just a single CSS file) doesn't get loaded. Following is how I am trying to load the CSS file.
{% load static %}
<link rel="stylesheet" type="{% static 'homepage/css/style.css' %}" href="PATHTOCSSHERE">
The developer tool of chrome also doesn't show the app level CSS file in the list of loaded files, which clearly means that the file doesn't get loaded.
You need to follow the template principle of putting your app-specific files inside another level of directory with the app name - for example /project/homepage/static/homepage/css.... Now your links will work (with your existing settings).
However unless you are actually distributing your apps independently, I don't find this a helpful way of organising things. Just use your project-level static directory, and have app-specific directories in there - /project/static/homepage/css.... Then you just need a single directory in STATICFILES_DIRS.
I am absolutely sorry everyone. Just saw an obvious mistake in my own code. The error has been resolved now. Thanks!

recommended location for static & templates directories

I am a little bit confused about the recommended location of the templates and static directories. Apparently it is better to have 1 templates directory in every app folder. Django automatically look for templates there. However it seems not to be the case for static, is it? Can I tell django to look for static within the directory of the app currently running (instead of a single directory in the root folder)?
Thanks.
you can manually setting django to look where static files are.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), # basic, noqa.
os.path.join(BASE_DIR, "blog/other_static"), # another static folder in blog app
)
Django will look those folders.
and one more, you may set your static folder like static/blog/js/some.js and static/otherapp/css/some_css.css.
You may make folder in static directory named same as your app.
And I'm not suggest managing your static files in your app directory unless you're going to use your app as reusable.

Django 1.4 (MEDIA_ROOT, STATIC_ROOT, TEMPLATE_DIRS)

I have a Django 1.3 project with this options in settings.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates'), )
But in Django 1.4 by default settings.py is moved in subdirectory with name that is equal to project name. Because of that static, media and templates directories now have to be moved in the same subdirectory?
Is this what I have to do, or just change STATIC_ROOT, MEDIA_ROOT and TEMPLATE_DIRS options?
I know that both variants are OK, but what is best practice for this in Django 1.4?
And also I know that every app can have it's own templates and static directories.
And is it better to put all other application directories inside the same subdirectory? This is not what is happening by default using manage.py startapp
OK the scheme that I follow is this:
myproject/requirements.txt - pip installable packages
myproject/deployment - Deployment stuff like server config files, fixtures(dummy data), etc.
myproject/docs - project's docs
myproject/tests - project's tests
myproject/myproject - project's operational code(and settings.py, urls.py)
Expanding myproject/myproject folder:
myproject/myproject/app1 - a regular app(encompassing its specific templates/static files)
myproject/myproject/app2 - another regular app(same as above)
myproject/myproject/website - semi special app, by convention.
This website app houses basically 4 things:
1) an empty models.py(so that django will consider it as a valid app)
2) a views.py with the entry point index view. Maybe some other views that don't fit in any other specific app.
3) a management dir with custom django commands which apply to the whole project.
4) a templates dir that has the 404.html and 505.html. Also it has a subdir called website that includes universal/base html templates that every other app extends, plus
the index.html.
5) a static dir with subsequent subdirs named css, js and media for global static files.
Nothing exotic I guess. I think that most people follow a similar pattern, but I would like to here any inefficiencies with this, if any.
EDIT:
with regards to settings for production VS development I use
the popular settings_local pattern, which you can read here and eventually will
lead you here, which describes a better pattern.

Django and staticfiles questions

The more I learn Django, the more I discover new things.
I read the official docs, stackoverflow and google but I still have doubts.
What's the correct/normal way to organize our static files?
I mean folders and settings.py
I have something like:
CURRENT_PATH = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(CURRENT_PATH, 'static')
STATIC_URL = '/static/'
Ok, Im going to collect all my apps statics on ~/static/
I created a static/appname folder on every app and I put all my app's static there.
Also, I need a static folder to project-wide statics (what's the common name for it? Since I used /static/ for collected stuff and they cannot be equal).
So far so good, I have css like:
href="{{ STATIC_URL }}appname/styles.css"
and it works like charm.
But I think that when I deploy my app, I have to run 'collectstatic' so I put that '/static/' folder serving on Cherokee.
The question is... will that work? I tried commenting the AppDirectoryFinder and the _DIRS one and that doesn't work on local (Having the static stuff collected, I mean, the css on /static/ and in the other folders too).
Is just better to have one static folder on root for all the project? And copy the admin css to that folder (AKA manually collectstatic).
The projects I see on github/bitbucket are ready to be deployed, I need to know the steps to go from dev to deploy.
Thanks!
I'll break this down as I use the django static app
url at which your static media will be served
STATIC_URL = '/static/'
this is used for 2 things
{{STATIC_URL}} in your templates and the static file url
and for hosting your static files in django (DEVELOPMENT ONLY)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
The location at which your files reside on the server
STATIC_ROOT = '/var/www/website/static'
this is used when you run collectstatic and is where your webserver should be looking
your file finder definition
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
I've used the default from django you can of course use more but here is the crux of what you are looking to know
'django.contrib.staticfiles.finders.AppDirectoriesFinder'
will find any folder named "static" that is inside an installed app
'django.contrib.staticfiles.finders.FileSystemFinder'
will tell django to look at STATICFILES_DIRS (this is your project wide static files)
which should be defined as a tuple
STATICFILES_DIRS = (
join( CURRENT_PATH, 'static' ),
)
where 'static' is whatever you want and you can add in as many other folders to monitor as you wish.
the sub directories you place inside each app ie:app/static/appname are not necessary but will ensure that files of the same name inside different apps don't overwrite files from other apps or your root static folders
all of this was taken from my own experience and https://docs.djangoproject.com/en/1.3/ref/contrib/staticfiles/
Also, I need a static folder to project-wide statics (what's the common name for it? Since I used /static/ for collected stuff and they cannot be equal).
Are you sure? I'm pretty sure I'm using the same folder to collect my static files and to hold my project-wide static files. Not sure if that's not recommended pracice, but it works for me.
Note that this is just on the deployment side; my codebase just has the project static files.

Django dev server intermittently fails to serve static files

In my development environment I'm getting intermittent failures for serving static files (js scripts and css). In the error console in Chrome I get 404s. But if I refresh on those items, or visit the URLs directly, they're served up fine.
This is annoying.
Example:
GET http://127.0.0.1:8000/static/js/editor/xyz.js?v=1 404 (NOT FOUND)
but if I visit that URL directly fine. And if I refresh the page a few times, it will work again.
Any ideas?
Chrome 14.0.835.202
Django==1.3
Fabric==1.0.1
Jinja2==2.5.5
PIL==1.1.7
Pygments==1.3.1
South==0.7.3
Sphinx==1.0.5
boto==2.0
chunks==0.1
django-devserver==0.2.1
django-pagination==1.0.7
django-sorting==0.1
django-storages==1.1.3
docutils==0.8
gunicorn==0.12.1
ipython==0.10.1
paramiko==1.7.6
pep8==0.6.1
psycopg2==2.2.2
pycrypto==2.0.1
python-dateutil==1.5
python-memcached==1.45
wsgiref==0.1.2
The dev server is single-threaded so if something keeps waiting, it blocks every request.
I usualy work with the django concurent dev server which is multi-threaded and works much better. Also it is very fast and easy to setup ;)
it might depends on your setup.
what did you do for the static? what's the settings? did you do the collect static?
try this in case
however, about serving static files in development:
Warning This will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure.
This is only intended for local development, and should never be used
in production.
from here
can't you just supply the static files in another server?
After reading all answers if still anyone having this problem then ...
As per Django nature you don't need to do anything to serve static files
just your settings file should have proper configuration as follows:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# **THIS IS USED WHEN YOUR STATIC FILES ARE IN SOME OTHER FOLDER ALSO**
# 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.
FOLDER_NAME,
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
# other apps
'django.contrib.staticfiles',
)
But if still you face problem put this into your urls.py:
(r'^(path of your file)$', 'django.views.static.serve' , {'document_root': 'PROJECT_ROOT_DIR' + "path to the static folder"}),
Above URL will serve for static files whether they are JS files or CSS or images.
In case of production server you don't need this.
Then run: python manage.py collecstatic.
Hope this helps.