简体   繁体   中英

Django - Serving statics with views and not with django.contrib.staticfiles

Im new in DJango and I need to change current static serving mode removing the /static Alias from Apache configuration (and relative STATIC_URL from default_settings)

 Alias /static/           /usr/local/app/static/

On django settings:

STATIC_URL = '/static/'

to a internal serving services using a local view.

I have added a new constant in settings.py

STATIC_WEB_ROOT = os.path.join(BASE_DIR, 'static/frontend/')

urls.py

from django.conf.urls.static import static

url(r'^%sstatic/(?P<path>.*)$' % , static  , {'document_root': STATIC_WEB_ROOT }, name='static.file.serve'),

index.html

<script type="text/javascript" src="{% url 'static.file.serve' 'frontend/js/jquery-3.2.1.min.js'                    %}" ></script>

Unfortunally, I get a 404:

"GET /static/frontend/js/jquery-3.2.1.min.js HTTP/1.1" 404

My settings was wrong in two points:

The correct module to import in urls.py is:

from django.views.static import serve

In default settings you have to disable, if exists:

'django.contrib.staticfiles'

that is the classical way to expose statics

Then in the url you can use:

url(r'^%sstatic/(?P<path>.*)$' % BASE_URL_PREFIX  , serve  , {'document_root': STATIC_WEB_ROOT }, name='static.file.serve'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM