In the documentation https://docs.djangoproject.com/en/dev/howto/static-files/
I read that static files should be put with their respective apps and called upon with
{% load staticfiles %}
<img src="{% static "articles/css/base.css" %}" alt="My image"/>
However later on in the docs it mentions that some static files don't pertain to a particular app. This is where STATICFILES_DIRS comes into play. If I read correctly STATICFILES_DIRS is a tuple for Django to use to look for other static files. I was wondering how would I call the static files that was called from the STATICFILES_DIRS?
ex: something like
<link rel="stylesheet" type="text/css" href="{% static "/css/default.css" %}">
Also I am not sure what to put for my STATIC_ROOT. Do I leave it empty? ('')
My proj tree
mysite
\articles
\static
\articles
\css
base.css
\static
\images
\css
default.css
\js
\templates
base.html
\settings.py
This is currently in my settings.py regarding static files
# looks for static files in each app
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_STORAGE = (
'django.contrib.staticfiles.storage.StaticFilesStorage'
)
# the absolute path to the directory where collectstatic will collect static files for deployment (OUTPUT)
STATIC_ROOT = ''
# This setting defines the additional locations the static files app will traverse if the FileSystemFinder finder is enabled.
STATICFILES_DIRS = (
# used for static assets that aren't tied to a particular app
os.path.join(BASE_DIR, 'static'),
)
# URL to use when referring to static files located in STATIC_ROOT
STATIC_URL = '/static/'
Almost everything about django static is related to the django.contrib.staticfiles app. Although you need to custom edit many settings to make staticfiles work, what is does is simple. It provides a collectstatic command which collects static files from different app and put them into a single directory.
The answer to your first question is simple: Put those common static files under the /static directory of your django project directory. In your case, it's mysite/static.
Reason: First, it's the official way. You can find the following code in official doc: Managing static files (CSS, images). Second, it's reasonable. Since we put static files only used in a single app under project/appnane/static/... The project's static dir should follow the same name pattern.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), # That's it!!
'/var/www/static/',
)
As I said in the comment, your should not set STATIC_ROOT to project_absolutr_path/static. Because that directory is user to put css app static files. You don't want the collectstatics command to pollute that directory especially when you are using a version control system like git/svn.
STATIC_ROOT really depends on the way you host these static files(Apache, Nginx, S3, CDN, Paas like heroku)
Related
Here's my script in base.html, the left of the picture is about my tree.
I checked the href should be correct and I've load static at very top of the html file. However I still cannot connect the css file anyone can help he here? Thanks!
href="{% static 'Simple_Social/css/master.css' %}"
for refer, please see the picture since idk why I can't post a picture yet, thanks!
https://i.stack.imgur.com/Vi2z6.png
This is how static files are configured. In settings.py file inside the INSTALLED_APPS list, there is an app called 'django.contrib.staticfiles', this baked in app manages the static files across the entire project during development as well in production.
This static URL will append to base URL for serving static files in development like http://127.0.0.1:8000/static/css/style.css basically think this as a reference to static files.
STATIC_URL = '/static/'
STATICFILES_DIRS tells Django the location of static files in our project. The common practice is to have all the static files in a top-level static directory.
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT is the single root directory from where the Django application will serve the static files in production. The command manage.py collectstatic will automatically compile all the static files throughout the project and dump it into a single root directory, which is declared in STATIC_ROOT.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Finally, you can user load static to load the static files in template
{% load static %}
I'm just at my wits end here. I want to load my custom js files from the static folder.
When I view the source on Chrome, it's not showing up and it's not being loaded when I refresh the page.
What it looks like on Chrome (and I can't click on my file, while the jQuery does light up):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>
<script src="/static/js/ajax.js"/>
UPDATE:
Here is what I have now, but it's still not working
base.html
{% load staticfiles %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>
<script src="{% static 'js/ajax.js' %}"/>
settings.py
STATIC_ROOT = 'static/'
STATIC_URL = 'assets/'
STATICFILES_DIRS=(BASE_DIR, 'assets')
I ran python manage.py collectstatic and it copied a bunch of files over.
Here is a layout of the updated structure. You can see that the ajax.js was copied over but it's still not showing up when I run the server. Any ideas?
What am I missing?? Please help.
Python 2.7, Django 1.7
Obligatory reading:
https://docs.djangoproject.com/en/1.7/howto/static-files/
https://docs.djangoproject.com/en/1.7/ref/contrib/staticfiles/
https://docs.djangoproject.com/en/1.7/ref/settings/#static-files
About these settings:
STATIC_URL = 'assets/'
This means that your app should serve static files with assets/{name} prefix.
I think this is the source of your problem - the initial / is missing and you're generating relative links for static resources, which sounds like a Bad Idea.
Now a page at http://yourserver/foo/bar/ would ask for static files via a relative link:
<img src="assets/{name}">, so your browser would look in /foo/bar/assets/{name} and find nothing.
You'd normally want an absolute link for static files, so instead you should use STATIC_URL = '/assets/' and obtain absolute links <img src="/assets/{name}">.
STATICFILES_DIRS=(BASE_DIR, 'assets')
Okay, so how does Django find the static files? A Django project can have many installed applications, and each application can have its own directory with static files.
So there's this setting (set by default):
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
This means that, on development setup (runserver), whenever someone asks for http://yourserver/assets/ponies/applejack.jpg (where /assets/ is your, now hopefully fixed, STATIC_URL), Django would try to find a file ponies/applejack.jpg in the following way:
first by using FileSystemFinder that looks in some fixed directories you specify (STATICFILES_DIRS),
second by using AppDirectoriesFinder that looks into the static/ subdirectory of each of your INSTALLED_APPS.
So if you want to keep your static files per-app, you don't need to rely on FileSystemFinder and you can leave STATICFILES_DIRS empty.
But if you want to keep all the static files in one place, point STATICFILES_DIRS to any directory like you did. You should still keep AppDirectoriesFinder for third party apps you use, like the Django Admin, that come with their own static files.
STATIC_ROOT = 'static/'
This is unnecessary for development setup with runserver because Django dev server serves your static files itself.
For production, however, you probably want your web server (Apache, Nginx, ...) or a content delivery network to handle the static file delivery for you. You can then use the collectstatic command to collect all the static files from everywhere (e.g. all static files your STATICFILES_FINDERS can find), and put them all in one directory on your machine, from where you can easily pass them on to Nginx or copy over to a CDN.
Do you have this in your settings?
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Currently I have my settings.py regarding static files set up like so
STATIC_ROOT = ''
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIR = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = '/static/'
From reading the documentation and various blogs my understanding is that STATIC_ROOT is where the static files go. It is the absolute path to the directory where collectstatic will collect static files for deployment (OUTPUT). I am not sure what to put this value as
For STATICFILES_DIR This setting defines the additional locations the static files app will traverse if the FileSystemFinder finder is enabled. So I would NEED a STATICFILES_FINDER field in my settings.py and in that field would be
('django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder')
However, by default STATICFILES_DIR is not included in my settings.py so I added it in.
For STATIC_URL is the URL to use when referring to static files located in STATIC_ROOT. I simply left it as the default setting because I am not sure how edit this.
I am not sure how to edit my settings.py regarding static files in order to display them onto a webpage. What is a "Best Practices" way to include static files onto a webpage?
ex: {% static "static/css/default.css" %}
I read a bit about namespacing as well but I am confused about this too
ex:
STATICFILES_DIR = (
("asserts", os.path.join(BASE_DIR, 'static')),
)
Best practice would be keeping each app's static files in it's own 'static' dir and running manage.py collect_static each time some static file changes.
Then, if you use default storage your files would be copied into STATIC_ROOT directory.
(But you might use custom storage, for ex for storing static files on Amazon S3 cloud)
And finally, STATIC_URL defines how your static files would be accessible from outside. In case of django dev server- it has static files app, that serves them under STATIC_URL location. In case of production server you definitely want to serve static files with either nginx/apache or with amazon S3/cloudfront (or other cloud services). In case ouf serving with nginx/apache, you must set STATIC_URL so {% static "static/css/default.css" %} will be replaced with the url relative to STATIC_ROOT, at the same time you should have this STATIC_URL location overriden in nginx/apache settings, so when final user tries to access it, it gets static file served w/o even touching django. In case of custom storage- this storage might provide it's own url (to S3 cloud for ex).
I've been trying to follow every single tutorial and thread there is, i jast cant get it togheter.
Sorry, but please exlpain it to me as if i was three years old..
What i have:
a CSS that i'd like use, styling a template.
How to get there:
MD: project/app/static/
place style.css there
settings.py:
STATIC_ROOT = '/project/app/static/'
STATIC_URL = '/static/'
(Should'nt this at least give me the string '/static/', when i try printing {{ STATIC_URL }} in the template..?)
template:
<LINK REL=StyleSheet HREF="{{ STATIC_URL }}/style.css" TYPE="text/css" MEDIA=screen>
Seems to me, the next logical thing would be to create an /static/-url aswell?
I'm really lost here..
Django's staticfiles system is about two things:
Combining static files from a number of (app-specific) directories into a single place from which they can be served
Serving those files over HTTP
You want #1 if you have a number of static files located in different directories. You want #2 if you want to see those files while you are using the development server. In production, you usually skip #2, because the purpose of #1 is to put the files somewhere that your web server can access them.
Organizing and collecting static files
With that said, here's how you get #1:
settings.py:
# This is a filesystem path
STATIC_ROOT = '/path/to/my/project/collected-static-files/'
# This is a URL prefix
STATIC_URL = '/static/'
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
...
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
)
At this point, you can do a few things:
You put your static files in an '/static/' directory under each of your apps. That's where django will look for them. There is an additional setting, STATIC_DIRS, that you can use if you have static files that are outside of your apps.
You can run manage.py collectstatic to have Django go through all of your apps, finding all of the static files, and copying them into /path/to/my/project/collected-static-files (That's why that setting is a filesystem path.)
You can use {{ STATIC_URL }} in templates to access the files.
Serving static files over HTTP
In development mode, under the dev server, Django will automatically serve files out of the STATIC_ROOT directory.
Basically, Django will add a URL handler for URLs of the form
/static/some-dir/some-file-name
And serve content from your hard drive, from the filesystem path
/path/to/my/project/collected-static-files/some-dir/some-file-name
In production, this won't happen automatically, so you will have to configure your web server to do the same thing. (It's just not a good idea to run all of your static files through Django's full processing pipeline. The web server can do it much more efficiently)
I have downloaded a template online that includes a base html file, images and a css file. Now I would like to implement all this in django.
So far I tried like this but with no good results, the page gets rendered without css file or without images, or both... well something is wrong
settings.py:
MEDIA_ROOT = rel('resources')
MEDIA_URL = '/resources/'
base.html:
<link rel="stylesheet" type="text/css" href="resources/style.css" />
I have put my images and the css file in the resources folder and the templates folder and it doesnt work, please help
EDIT:
I was slightly off there... STATIC_ROOT refers to the directory where Django will collect all static files. STATICFILES_DIRS is a list of searchpaths for static files. So like this:
settings.py:
# 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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = PROJECT_ROOT + 'static/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# 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.
"C:/www/django/static",
)
# 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',
)
and add the url to urls.py:
urlpatterns += staticfiles_urlpatterns()
ORIGINAL ANSWER:
This can be quite confusing.
The MEDIA_ROOT directory is for files uploaded via a file-upload form. For physical files that are directly accessible by client request (e.g style sheets, scripts and images) you have to use the STATIC_ROOT and STATIC_URL. STATIC_ROOT must be an absolute path i think.
settings.py
# the url: myserver.com/static/
STATIC_URL = '/static/'
# refers to this directory:
STATIC_ROOT = '/home/user/static server files'
let's say you put your css in "/home/user/static server files/css/" then refer to them like this:
base.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" />
Assuming you are working on a development server for now .
MEDIA_URL = 'http://localhost/media/'
calculated paths for django and the site
used as starting points for various other paths
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
PROJECT_ROOT = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates/'),
)
MEDIA_ROOT = os.path.join(SITE_ROOT, 'templates/media/')
The above should solve your problem as iot worked for me just fine.
While referring css files which are kept in "templates/media"
<link href="/media/css/base/base.css" rel="stylesheet" type="text/css"></link>
Hope this helps you out
hmm unfortunately this did not help. I could not find a variable STATIC_URL/ROOT in settings.py, so I added it as described above, also added the variable in base.html, but rendering still cannot find css file.
Another this I did is investigated code that works. I got a piece of good public application's source code and inspected base.html, and it says like this:
<link rel="stylesheet" href="{{ cssRootUrl }}style.css"
then I went to check the settings.py and cssRootUrl was not defined there. So I have no idea where else could this kind of variable hide...
this can solve your problem. I suggest you name your folder "static" for static files that you are using (css, js and images).
open your settings.py and
-add this at the first line of your file:
import os.path
-change your STATIC_ROOT's value to:
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
-change your STATIC_URL's value to:
STATIC_URL = '/static/'
create a folder named "static" in your project root.
create a folder for your static files like css, javascript and etc. I recommend you use a different folder for different types of files.
open the urls.py of your project
-add this to your imports: import settings
-add this to the url patterns:
(r'(?:.*?/)?(?P(css|jquery|jscripts|images)/.+)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT }),
NOTE: In this example, there are folders named css, jquery, jscripts and images inside my static folder.
In your template add this:
for css files: (in this example, default.css is the name of the css file)
<link href="/{{ STATIC_ROOT }}css/default.css" rel="stylesheet" type="text/css" media="all" />
for javascript:
<script type="text/javascript" src="/{{ STATIC_ROOT }}jquery/jquery.js"></script>