Reputation: 372
I am working with Django 3.2 and I have 3 types of static files (images, css files, js files).
I did not want the images to be versioned with git so I found a way to have them served by an aws S3 bucket using django-storages
and boto3
. It works perfectly fine with the following configuration in my settings.py
file:
AWS_ACCESS_KEY_ID = "my-key-id"
AWS_SECRET_ACCESS_KEY = "my-secret-key"
AWS_STORAGE_BUCKET_NAME = "my-bucket-name"
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
#DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_S3_ADDRESSING_STYLE = "virtual"
AWS_S3_REGION_NAME = 'my-region'
AWS_S3_SIGNATURE_VERSION = 's3v4'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Whilst this configuration works perfectly fine, it forces me to have my CSS and js files in the AWS s3 bucket as well. I was perfectly happy with my CSS and js files being served by django (or NGINX in production) and versioned with my code without having to copy them to the bucket manually.
Would you have a solution to serve only static images by AWS S3 and CSS/JS files by NGINX ?
Upvotes: 1
Views: 188
Reputation: 9325
{% static ... %}
is just a template tag which is a function that builds the whole URL based on given value and STATIC_URL
from settings.py. When Django serves static files in dev it maps STATIC_URL
prefix from an URL to STATIC_ROOT
and thus resolves file location.
To serve static files with NGINX you only need to generate correct URLs in templates. Mapping URLs to files will be done by NGINX via config location -> root/alias
.
One of possible solutions is to divide URLs (URL prefixes) for images and scripts by implementing your own "static" template tag generating URLs you need. e.g.
@register.simple_tag(name="static_script")
def static_non_image_files(path):
return urllib.parse.urljoin(settings.STATIC_SCRIPTS_URL, path)
and use this template tag in place of static
for scripts like {% static_script "/style/main.css" %}
. Whilst using static
for images on S3. Thus you'll be able to map different types of static files to different storage engines.
Upvotes: 1