简体   繁体   中英

Serving static files in development

I've got some static files that are currently serving from Amazon S3. This obviously isn't effective because I can't collectstatic every time I make a minor change. Whenever I'm developing I want to serve from my project where the static files are collected from. The project structure looks partially like this:

myproject
-app
--templates

-myproject
--static
---app
----css
----js
----img

My settings.py looks partially like this:

STATIC_ROOT = 'staticfiles'

MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')

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

AWS_HEADERS = {
    'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
    'Cache-Control': 'max-age=94608000',
}

AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

if DEBUG:
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
    STATIC_URL = '/static/'
else:
    STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN


STATICFILES_LOCATION = 'static'

MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

What I'm trying to achieve is that if I'm running development (when DEBUG would be true) serve static files from the project, rather than fetching from S3.

At the end of my urlpatterns in urls.py I have + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) .

Finally, in my base.html I have:

<!doctype html>
...
  <link rel="stylesheet" href="{% static '/css/normalize.css'%}">

If I'm running with debug=True and I view the source of the page I see <link rel="stylesheet" href="/css/normalize.css"> which isn't where the file is. If I run with debug=False and view the source I get <link rel="stylesheet" href="<AMAZON BUCKET>/css/normalize.css"> .

What am I missing to serve locally?

您必须将相对路径传递到static模板标签,而不能使用斜杠:

{% static 'css/normalize.css' %}

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