Getting background-image from GCP storage bucket using django static

241 views Asked by At

I am using django-storages GCP storage backend to serve static to my site from a storage bucket. However, I'm encountering an issue with using the background-image CSS property in conjunction with django's {% static %} tag. In particular, I have the following CSS embedded into the page:

<style> 
.my-background {
     background-image: url({% static 'foo/bar/example.jpg' %});
}
</style>

And then if I include the following in the HTML for the page:

<div class="my-background"></div>
<img src="{% static 'foo/bar/example.jpg' %}">

The <img> tag retrieves the image just fine, but the background-image gets a 403 error with AccessDenied returned from the storage bucket call. I can't figure out why they should be treated differently, any help much appreciated.

1

There are 1 answers

0
AlonzoCathedral On

I figured out a solution: including the background-image: url({% static 'foo/bar/example.jpg' %}) in a separate <style> tag fails, but it works if the background image is specified in an inline style instead. I suspect this is due to django storages using signed URLs to access the storage bucket, which had perhaps expired between the time the style tag was loaded and the call was made to the storage bucket.