Utilizing Django to display AWS S3 static files as background images in CSS

I've encountered some challenges when trying to display my static data using the css background-image tag.

For instance, consider the following code snippet:

<section class="banner-area" style="background-image: url('../../static/main/img/search4.jpg')>;

Upon inspecting the element in my browser, I noticed that it is not being linked to my AWS S3 bucket and the URL remains unchanged as shown below:

url('../../static/main/img/search4.jpg')

However, when I use the source tag to render an image, everything works as expected. For example:

<img src="{% static 'main/img/search4.jpg' %}/>

By examining the element in the browser, I can see that it is now properly linked to my S3 bucket, like so:

src="https://mybucket-bucket.s3.amazonaws.com/main/img/search4.jpg?ETC...."

In my settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
    
        os.path.join(BASE_DIR, "main/static"),
    
                        )
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img')
MEDIA_URL = "/media/"
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL='https://mybucket-bucket.s3.us-east-2.amazonaws.com/'

Any advice on this matter would be greatly appreciated.

Best regards, Marvin

Answer №1

Consider making the following change:

url('../../static/main/img/search4.jpg')

Replace it with:

url('{% static 'main/img/search4.jpg' %}')

The reason behind this adjustment is that your website is hosted on a different domain than your s3 bucket, causing issues in resolving the relative URL by the browser.

For instance, if your site is at example.com, the browser tries to adjust the URL based on the domain structure by removing the last 2 path components (parts of the URL after slashes e.g. /component1/component2/), resulting in no action being taken. To avoid this, you should include the relative path directly in your CSS file since it shares the same domain as your image.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Laravel 7 to establish a connection between Order ID and User ID, allowing you to retrieve

I need to retrieve the user name of the user who created an offer based on the seller's ID. In my database, I have 2 tables: First table User User | | - id | - name And the second table is Orders: Orders | | - id | - seller (User id ...

Tips for aligning box position in CSS regardless of screen size fluctuations

My header code includes: <link href="styles.css" rel="stylesheet" type="text/css"></link> The script placed in the body is: <input name="search" type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content" ...

The CORS policy has blocked access to the XMLHttpRequest from 'http://localhost:3000' to 'http://localhost:8000/api/posts/'. This issue is commonly encountered when using Django and React together

I am currently working on a project that involves using Django and React to build a full-stack application. One interesting component I created is a lookup feature that utilizes cookies. Here is the code snippet: function getCookie(name) { var cookieV ...

How can you generate unique URLs for user uploaded items in Django?

When a gif is uploaded to gfycat, it creates URLs like ForkedTestyRabbit which allows users to view the uploaded model instance. I'm considering generating a random unique URL after uploading, such as /uploads/PurpleSmellyGiraffe. The model will incl ...

When hovering, transition occurs unless the cursor is over a specific element

I have created a small box element with a close button that looks like this: ___ | X| ‾‾‾ In order to make it more interactive, I applied some CSS so that when hovered, the box expands like this: ___________________ | X| ‾ ...

How can I eliminate the empty spaces around a bar chart in Kendo UI?

Struggling to eliminate the extra space surrounding the Kendo UI chart below. Could this be due to a gap or spacing issue? The goal is to create a single-line bar chart with only grey appearing on the right side. Access JSFiddle Codes Here $(doc ...

The value of the innermost dropdown in the AngularJS Cascading dropdown is not being retrieved when it is selected

CSS <div ng-controller="DynamicCtrl"> <h1>Dynamic - Focused</h1> <p>This method works well when data is constantly changing</p> <div> Category: <select id="category" ng-model="items" ng-options="category ...

The navigation bar appears to have a different width on mobile view specifically on one page

I created a mobile view navigation that appears correctly on two out of three pages. It spans the full 100% width as intended, but on one page it extends beyond that and causes the layout to look distorted due to the larger navigation bar. I'm not sur ...

CSS animations - transitioning opacity in and out

Looking to add some CSS animations to a menu but running into some issues. I've got the code below for the menu to fade in on hover, but can't quite figure out how to make it fade out smoothly as well. I've tried a few approaches, but all I ...

What is the best way to display a List of QuerySets in a GraphQL query as individual list items?

The challenge I am currently tackling involves a custom_filter within MyModel, which returns a list of <QuerySet> as follows: [<QuerySet [<MyModel: xyz>]>, <QuerySet [<MyModel: xyz>, <MyModel: xyz>,<MyModel: xyz>]> ...

Invoke a method in a separate class

I am facing issues with passing variables to another file. I have checked my code multiple times but cannot find a solution. It keeps giving me an error in the function. onclick="limit();javascript:AyudaTipos(2)"/> The function is: function limit ( ...

Tips for emphasizing a table row according to its value

I am currently developing a Google web application that involves CRUD data generated from Google Sheets. The search function is working perfectly, but I am trying to enhance it by highlighting specific rows based on the data value in Column 7. For example ...

How to insert an image into a table using FPDF in PHP

I am working on some HTML: $html='<table width="100%" class="p" id="tblExport"><tbody> <tr><th>#</th><th>product</th><th>picture</th><th>product_category</th><th>avl_qty</ ...

Having trouble with aligning HTML elements with Bootstrap v4 framework

In the header, I have a container for the logo and another one for the login form. I want the logo to be on the left and the login form to be positioned at the top right corner. However, when I use float-left for the logo container and float-right for the ...

Table Construction Repeater Separator Blueprint

I've created repeaters in the past, but I haven't had much experience adjusting table layouts with them. Currently, my repeater is successfully populating data in a single column. However, I would like it to display in 4 columns. I was advised th ...

How to make text fade using CSS gradients top and bottom?

I am trying to create a fade effect for a paragraph from both the top and bottom. However, I am only able to achieve the fade effect from either the top or the bottom. HTML: <p className="bottom-overflow-fade"> {content} </p> CSS: ...

Utilizing the CSS properties of table-cell and float in a display

I've designed a header section, but I'm facing an issue. It looks good on devices with resolutions greater than 1020: https://i.sstatic.net/VlgmR.png https://i.sstatic.net/x3V15.png The problem arises on smaller resolutions: https://i.sstatic. ...

What is the reason for the disparity between CSS box-sizing content-box and border-box?

Consider the following example where I only changed the CSS box-sizing property from content-box to border-box. The resulting output difference is significant. Give this code a try: .box1 { width: 300px; height: 100px; border: 1px solid blue; pa ...

Explaining the purpose of the HTML5 label for attribute

In the HTML5 final specification, there is a quote regarding the use of the `for` attribute: The `for` attribute can be used to specify a form control that the caption is associated with. If this attribute is used, its value must be the ID of a labelabl ...

Having trouble accessing property '0' of undefined in angular

Below is the code I am currently working on. My goal is to enable editing of the table upon click, but I encountered the error mentioned below. Could someone kindly explain why this is happening and suggest a workaround? <tbody> <tr *ngFor="l ...