Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT

What are the differences of these three static url?

I am not sure if I am right, I am using the MEDIA_ROOT to store my uploaded photos (via models.ImageField())

However, I created a JS script to my admin and in admin.py. I defined the media as below:

....
class Media:
      js = ('/admin/custom.js', )

and my settings.py:

 ....
 STATIC_ROOT = "/home/user/project/django1/top/listing/static"

and I added the custom.js to STATIC_ROOT/admin/custom.js, but it is not working. Throwing 404 not found error.

And then I change the STATIC_ROOT to STATICFILES_DIRS, and it works!!

....
STATICFILES_DIRS = "/home/user/project/django1/top/listing/static"

So, I am not understand what is going on here. In fact, I just don't understand what is the difference between STATIC_ROOT and STATICFILES_DIRS.

Currently I am testing Django in my machine via virtualenv, not deployed yet, is it the reason STATIC_ROOT not working??

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Development

STATIC_ROOT is useless during development, it's only required for deployment.

While in development, STATIC_ROOT does nothing. You even don't need to set it. Django looks for static files inside each app's directory (myProject/appName/static) and serves them automatically.

This is the magic done by manage.py runserver when DEBUG=True.

Deployment

When your project goes live, things differ. Most likely you will serve dynamic content using Django and static files will be served by Nginx. Why? Because Nginx is incredibly efficient and will reduce the workload off Django.

This is where STATIC_ROOT becomes handy, as Nginx doesn't know anything about your django project and doesn't know where to find static files.

So you set STATIC_ROOT = '/some/folder/' and tell Nginx to look for static files in /some/folder/. Then you run manage.py collectstatic and Django will copy static files from all the apps you have to /some/folder/.

Extra directories for static files

STATICFILES_DIRS is used to include additional directories for collectstatic to look for. For example, by default, Django doesn't recognize /myProject/static/. So you can include it yourself.

Example

STATIC_URL = '/static/'

if not DEBUG: 
    STATIC_ROOT = '/home/django/www-data/site.com/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static/'),
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...