correct static files setting - python

Hello I'm very confused about setting static files up. Every thing works fine(displays image, javascript, css) no matter what I try. So I'm confused which one is the right one.
Currently, this is how my project looks like
project
--project
---------static
---------media
--env
--static
--------media
--------static
And this is my code
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "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',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
When I do python manage.py collectstatic, I don't get any error but static folder that's in outer static folder doesn't contain anything. but media folder that's in static folder contains the files in media folder that's in project folder.
Also
I have this for aws,
AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True
DEFAULT_FILE_STORAGE = 'project.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'project.utils.StaticRootS3BotoStorage'
AWS_STORAGE_BUCKET_NAME = 'realproject'
S3DIRECT_REGION = 'ap-northeast-2'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
import datetime
date_two_months_later = datetime.date.today() + datetime.timedelta(2 * 365 / 12)
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")
AWS_HEADERS = {
'Expires': expires,
'Cache-Control': 'max-age=86400',
}
Can someone please tell me if I'm doing it right?
by the way, I read https://docs.djangoproject.com/en/1.9/howto/static-files/
and followed it, i'm not sure if I followed it right(displayed above) which is why I'm asking.

The python manage.py collectstatic command looks for all your static directories and combines those file in the directory defined by the STATIC_ROOT setting.
In your case, STATIC_ROOT is set to os.path.join(os.path.dirname(BASE_DIR), "static", "static"), i.e.
your_project/static/static
So this is where the static files are being collected to. If you want them in the outer static directory, you can change STATIC_ROOT to os.path.join(os.path.dirname(BASE_DIR), "static").
There is a good discussion of this in the excellent Django docs here.
There is quite a lot to take in in these settings, so here is a quick summary of each static setting as an example:
# this is the URL that django will look for static resources at
# - i.e. http://your_domain/static
# so this one is a URL used when by your web server and in template
# shortcuts.
STATIC_URL = '/static/'
# this is where Django will look for static files to collect.
# I.e. the search locations that collectstatic uses.
# 'my_project/static' in this instance. You need to add the places
# you write your static files to this directory. For example, if you
# have several places where you are writing css files, add their
# container directories to this setting.
# it is a list of places to look for static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# this is where collectstatic will collect the static files to.
# When you hook this all into your webserver, you would tell your
# webserver that the /static/ url maps to this directory so that
# your app can find the static content. It's a directory in your
# project usually.
# it's a single directory where the static files are collected together.
STATIC_ROOT

Related

STATIC_ROOT setup in Django 1.8

I was tried n I can't set-up as per official documents...
I am attaching IMG here, pls give me suggestions, Where is the problem.enter image description here
Or, give me simple steps for it with dictionary tree structure.
Thank you.
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root', 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
# '/var/www/static/',
)
STATIC_ROOT = 'os.path.join(BASE_DIR, 'static_root', 'static') can't work.
Try this :
# define your base directory
# It will be `absolute/path/to/demo3`
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
# define where your static files will be collected
# It will be `absolute/path/to/demo3/static`
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# keep it empty for the moment
STATICFILES_DIRS = (
)
You have to understand STATICFILES_DIRS role :
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.
I recommend you to read carefully Django docs : Managing static files
STATIC_ROOT should be without quotes:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Also, the STATIC_ROOT folder shouldn't be named the same as the STATICFILES_DIR folder, so you should name it something like staticfiles instead:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATIC_ROOT = 'os.path.join(BASE_DIR, 'static')' is a string which is wrong.
it should be STATIC_ROOT = os.path.join(BASE_DIR, 'static')
The error is clear in stating the STATIC_ROOT is not a filesystem path. Django requires that STATIC_ROOT be an absolute path to a folder location on the machine. This error likely means that your resulting STATIC_ROOT is a partial or relative path. What is the value of BASE_DIR? After the line that sets STATIC_ROOT and a print(STATIC_ROOT) to see what value it is.
Try setting BASE_DIR as follows:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Other Errors
On the line
STATIC_ROOT = 'os.path.join(BASE_DIR, 'static')'
You have the value surrounded by single quotes. os.path.join() is a function call. Remove the quotes and change the line like this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Also, STATIC_ROOT cannot be included in the list of files in STATICFILES_DIRS. Consider setting the STATIC_ROOT folder to:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
when creating the project with latest version of python and django in settings.py file by default from pathlib import Path Statement is there.So in that case no need to use os.path.
from pathlib import Path # Import First
STATIC_ROOT = Path.joinpath(BASE_DIR, 'static_collected')
I added one line code and it worked for me, I hope it doesn't pain in the future :)
import os
Remember to create a static folder in your root directory and also create the static folder in your project folder. Then your file structure would be:
demo3
/demo3/staticfiles # collection folder for all static files
/static # root static folder
/userForms/static # your app static files
# OR
demo3
/demo3
/static_files # collection folder for all static files
/static # root static folder
/userForms/static # your app static files
Add this to your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'demo3', 'staticfiles')
OR depending on where you want the collection folder
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
Run python manage.py collectstatic
Then it would bundle all static files in project staticfiles OR root static_files folder, depending on where you want them.

django collectstatic adding extra /static/ folders

It's weird that everytime I run collectstatic consecutively it copies the static files to an extra static folder within the static folder:
First time I run it:
Copying '/var/www/django/abc/public-www/static//images/coro.jpg'
the second time I run it, it will copy the files as below:
Copying '/var/www/django/abc/public-www/static/static/images/coro.jpg'
third time:
Copying '/var/www/django/abc/public-www/static/static/static/images/coro.jpg'
This is what I have in settings.py
PROJECT_ROOT = dirname(dirname(__file__))
VIRTUALENV_ROOT = dirname(PROJECT_ROOT)
STATIC_ROOT = join(VIRTUALENV_ROOT, 'public-www', '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 = (
# 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.
join(PROJECT_ROOT,'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',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
I think I have found the culprit, I had this line for MEDIA_ROOT
MEDIA_ROOT = join(VIRTUALENV_ROOT, 'public-www')
Which should have been:
MEDIA_ROOT = join(VIRTUALENV_ROOT, 'public-www', 'media')
Once I changed it, collectstatic works as normal.

I can't define STATICFILES_DIRS using Python to figure out the path

I want to be able to define my settings for static/media files using python to get the paths so I don't need different settings on my dev machine and my server.
So I have these settings;
import os
from unipath import Path
### PATH CONFIGURATION
# Absolute filesystem path to the top-level project folder
SITE_ROOT = Path(__file__).ancestor(3)
### MEDIA CONFIGURATION
MEDIA_ROOT = SITE_ROOT.child('media')
MEDIA_URL = '/media/'
### END MEDIA CONFIGURATION
### STATIC CONFIGURATION
STATIC_ROOT = SITE_ROOT.child('static')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = os.path.join(SITE_ROOT, 'static'),
My problem is that locally it won't load the static files and the terminal says that STATICFILES_DIRS should not contain the STATICFILES_ROOT.
Is it possible to get Python to load the paths like this or am I wasting my time?
There's nothing wrong with your code per se, it's just that the point of the staticfiles app is to copy the files from the directories specified in STATICFILES_DIRS into the directory specified in STATIC_ROOT, so it doesn't make much sense to include the STATIC_ROOT directory in the STATICFILES_DIRS setting.
Unless you're actually using the staticfiles app with ./manage.py collectstatic, you may as well just leave the STATICFILES_DIRS setting empty, i.e. just change...
STATICFILES_DIRS = os.path.join(SITE_ROOT, 'static'),
...to...
STATICFILES_DIRS = ()
Do like this:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static/'),
)
That should work. Hope it helps!
+1 for both other answers. If you get tired of typing os.path.bla a lot here's a shortcut you can position at the top of your settings file (or import from anywhere else)
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
STATICFILES_DIRS = (
rel('static'),
)

Django Static Files results in 404

Ive checked over quite a few of the other threads on being unable to serve static content using the static file app within Django but as yet have yet to find a solution.
settings.py
STATIC_ROOT = '/opt/django/webtools/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/html/static",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Template
relevant line....
<img src="{{ STATIC_URL }}macmonster/img/macmonster-logo-blue.png" >
Logs
From the logs it looks like the path is correct, but alas it is still resulting in a 404..
[10/Feb/2013 16:19:50] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
[10/Feb/2013 16:19:51] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
For local serving of static files, if you haven't set up any form of collecting of staticfiles and if you're running Django 1.3+, I believe this is the way your settings.py should look like when refering to static files
# 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 = ''
# 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.
'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/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',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Notice that I've left out the STATIC_ROOT here.
This is because I don't have the need for static files collection "just yet".
The collecting of static files is to allieviate(spelling) the problems with serving multiple diffrent staticfiles folders, so they merged the staticfiles app that was used normally for helping with this problem.
What this does, and it's described in the docs, is to take all the static files from all your apps and put them into one (1) folder for easier serving when putting your app into production.
So you're problem is that you've "missed" this step and that's why you're getting a 404 when trying to access them.
Therefore you need to use a absolute path to your static files ie. on a mac or unix system it should look something like this:
'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/static',
Also, you could simplify and "fix" the need of having a hardcoded path like that which I used for illustration and do like this
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = (
PROJECT_ROOT + '/static/'
)
This would fix the portability problem as well. A good Stackoverflow post about that is found here
I hope I made it a bit clearer, otherwise please correct me if I'm wrong ^_^!
For collecting and how to manage static files in the newer versions of Django read this link
The staticfiles app
Change
STATIC_URL = '/static/'
set
STATIC_URL = 'http://yourdomain.com/static/'
it's unbelievable but, after 1 hour searching it solution solve my problem with static files and remove STATIC_ROOT from STATICFILES_DIRS.
STATICFILES_DIRS is just for collecting all the static in modules and store it in STATIC_ROOT.

How do I display an image on my webpage in Django?

I want to display an image on my website. I've been looking through the Django documentation and the other posts on stackoverflow, but I haven't gotten this to work.
I have an image name 'under-construction.jpg'. It lives in the /home/di/mysite/myapp/static/images directory.
I have a template like this:
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
in my views.py I have this:
def under_construction(request):
return render(request, 'under_construction.html')
In my settings.py, I have this:
STATIC_ROOT = ''
# 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.
'/home/di/mysite/myapp/static',
'/home/di/mysite/myapp/static/images',
)
I executed ./manage.py collectstatic and it put a lot of files in /home/di/mysite/admin and /home/di/mysite/images. What do I have to do get my image to show up?
All you need to do is edit settings.py to be as the 4 following points and create a new folder (static) in the same folder settings.py is located
in the folder static you can create another folder (images) in it you can put the (under_constructioon.jpg)
STATICFILES_DIRS = (os.path.join( os.path.dirname( __file__ ), 'static' ),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)
STATIC_URL = '/static/'
STATIC_ROOT = ''
after you're done with the prev. points you can write
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
I have faced same problem displaying the static image. suffered a lot and spent a lot lot of time in this regard. So thought to share my settings.
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
import os.path
STATICFILES_DIRS = (
"D:/temp/workspace/offeronline/media",
(os.path.join( os.path.dirname( __file__ ), 'static' )),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ... and at the end of the file add the following line
urlpatterns += staticfiles_urlpatterns()
and finally added the following code to the template tag and it worked
<img src="{{ STATIC_URL }}images/i1.png" />
I have solved that problem like this.
STATIC_ROOT = '/path/to/project/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
Django will not directly get files directly even you do this. You need to link this static directory for each application of yours. Just go to the django app dir run following command..
cd /path/to/project/my_proj/my_app
ln -s /path/to/project/static/
This will work only in debug mod. You need to set DEBUG = true in settings.py file. This should work with django's development server.
Django won't serve any static file in production mod. You need to serve static files with web-server in production mod.
More information can be found here..
Django does support static files during development, You can use the django.views.static.serve() method in view to serve media files.
But using this method is inefficient and insecure for production setting.
for Production setting in Apache
https://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#serving-media-files
set STATIC_ROOT = /path/to/copy/files/to
have you added
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'),
or you can also do this
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
and of course try not to server static files through django it does have some overhead instead configure your http server to serve them, assuming you have an http server (nginx is quite good).

Categories

Resources