Django static files on AWS S3 Bucket - django

There are a bunch of questions similar to this one, but after going through some of them, I still can't get it right.
I have a Django app and I want to serve static and media files using an AWS S3 Bucket. I can run python manage.py collectstatic and the files are added to the bucket. However, I am getting a 404 not found error for static files on the browser. There was a point in time that my configurations worked because I was able to see the files coming from s3 by inspecting the page, but I can't find what was changed for it not to work now.
Here's my settings.py:
USES_S3 = os.getenv('USES_S3') == 'True'
if USES_S3:
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=31536000'}
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'core.storage_backends.StaticStorage'
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'core.storage_backends.MediaStorage'
else:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles')
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (
os.path.join(CORE_DIR, 'core/static'),
)
storages_backend.py:
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media'
default_acl = 'public-read'
file_overwrite = False
class StaticStorage(S3Boto3Storage):
location = 'static'
default_acl = 'public-read'
I also tried to set the following variables, with no success:
AWS_S3_SIGNATURE_VERSION = 'virtual'
AWS_S3_REGION_NAME = 'eu-west-3'
AWS_S3_SIGNATURE_VERSION = 's3v4'
Any idea what could it be? I don't understand how collectstatic works and creates the files on the bucket but then I get 404.
Here's also an example of one of my html files (this one is the base.html):
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<title>
</title>
<!-- HTML5 Shim and Respond.js IE10 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 10]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Meta -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="canonical" href="https://appseed.us/admin-dashboards/django-dashboard-dattaable">
<!-- Favicon icon -->
<link rel="icon" href="/static/assets/images/favicon.ico" type="image/x-icon">
<!-- fontawesome icon -->
<link rel="stylesheet" href="/static/assets/fonts/fontawesome/css/fontawesome-all.min.css">
<!-- animation css -->
<link rel="stylesheet" href="/static/assets/plugins/animation/css/animate.min.css">
<!-- vendor css -->
<link rel="stylesheet" href="/static/assets/css/style.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
<link href="{% static 'ronfe.css' %}" rel="stylesheet" type="text/css" />
<!-- Specific CSS goes HERE -->
{% block stylesheets %}{% endblock stylesheets %}
</head>
<body>
<!-- [ Pre-loader ] start -->
<div class="loader-bg">
<div class="loader-track">
<div class="loader-fill"></div>
</div>
</div>
<!-- Top Bar -->
{% include 'includes/navigation.html' %}
<!-- SideBar -->
{% include 'includes/sidebar.html' %}
<div class="pcoded-main-container">
<div class="pcoded-wrapper">
{% block content %}{% endblock content %}
</div>
</div>
{% include 'includes/scripts.html' %}
<!-- Specific Page JS goes HERE -->
{% block javascripts %}{% endblock javascripts %}
</body>
</html>

Related

How to load a static file in django v4.0.5?

I was trying to load a static file i.e my CSS in django and i am doing evrything taught in tutorial but it isn't happening. i have my CSS inside static folder.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">
<title> Django </title>
</head>
<body>
<header>
<div>
<nav id="a1">
Home
About
Contact
Courses
</nav>
</div>
</header>
Here, is my settings.py file as i was following tutorial,
settings.py
STATIC_URL = 'static/'
STATICFILES_DIR=[
BASE_DIR,"static"
]
IN settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
IN urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^static/(?P<path>.*)$', serve, {"document_root":settings.STATIC_ROOT}),
]
If your DEBUG is False then you need to run python manage.py collectstatic

Django cannot find images

I use Django ,everythings works perfectly fine but i cannot load images.
My settings.py file
STATIC_URL = '/static/'
STATICFILES_DIR=[
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT=os.path.join(BASE_DIR,'assets')
My html file
<!DOCTYPE html>
{% load static %}[enter image description here][1]
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>First App</title>
</head>
<body>
<h1>Yeah..! this is index.html file</h1>
<img src="{% static "images/pic1.jpg" %}" alt="Nothing to show">
</body>
</html>
Tree directory
Typo in settings.py, it's supposed to be
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]

CSS not applying to HTML page when receiving a new render in Django

I am currently struggling on a problem of HTML response.
I have an HTML page with CSS,JS working fine, the user will do an interaction that will go to JS -> send ajax request and do some treatment within a working view. And this view give me back a rendered view with all the info updated.
The problem is that the HTML given is containing everything but looks like "raw" HTML a.k.a no CSS applied to it, (scripts are working fine)
In the head of my HTML file :
<head>
<meta charset="utf-8">
<title>Sorting video: {{video.title}}</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'modelReco/cssFiles/swipeFrames.css' %}?v=00002'">
<script type="text/javascript" src='{% static "modelReco/jsScript/swipeFrames.js" %}?v=00003'></script>
</head>
The view that render the HTML:
def sendSortVideoResponse(request,untreatedFrame,myVideo,frames,tracks,url):
response = render(request, url, {
'video':myVideo,
'frames':frames,
'tracks':tracks,
'untreatedFrame': untreatedFrame[0],
'countTreated': untreatedFrame[1],
'totalFrames': len(frames),
'progressBar': untreatedFrame[1]/len(frames)*100,
})
response["Cache-Control"] = "no-cache, no-store, must-revalidate"
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
return response
In settings.py :
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
If you F5 the page then everything works fine again.
For the user, the page he is on doesn't reload so it might be the problem but I have an other stylesheet doing a progressing bar working perfectly so I'm confused.
So it might be a bad use of static files
EDIT Network and page :
Before the interaction :
After the interaction :
EDIT 2 : The rendered HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sorting video: fashionShow2</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" type="text/css" href="/static/modelReco/cssFiles/swipeFrames.css?v=00002'">
<script type="text/javascript" src='/static/modelReco/jsScript/swipeFrames.js?v=00003'></script>
</head>
<body>
<h1>Video: fashionShow2</h1>
<p>What can you do on this page?</p>
<p>You've chosen to sort the video fashionShow2, this means you want to help the A.I to recognize the model by simply clicking on the models and validate your answer</p>
<div id = 7951 class = "untreatedFrame" style="zoom:.6;-o-transform: scale(.6);-moz-transform: scale(.6)" >
<img class = "frameImg" src="/media/fashionShow2/frames/7951.png"/>
<a class = "frameImg" style="top: 0%; left: 65%; width: 35%; height: 100%;" onmouseover="displayValidation('rightCorner',true)" onmouseout="displayValidation('rightCorner',false)" onclick="validateFrameChoice(7951,1,true,'/modelReco/sortedTracks')">
<div id="rightCorner" class = "validationCorner"></div>
</a>
<a class = "frameImg" style="top: 0%; left: 0%; width: 35%; height: 100%;" onmouseover="displayValidation('leftCorner',true),true" onmouseout="displayValidation('leftCorner',false)" onclick="validateFrameChoice(7951,-1,false,'/modelReco/sortedTracks')">
<div id="leftCorner" class = "validationCorner"></div>
</a>
</div>
<div class="w3-container">
<div class="w3-light-grey w3-round-xlarge">
<div class="w3-container w3-blue w3-round-xlarge" style="width:73.01587301587301%">46/63</div>
</div>
</div>
<input type="button" value="Cancel previous choice" onclick="cancelPreviousChoice(7951)" />
<form action="/modelReco/">
<input type="submit" value="Return to home" />
</form>
<script>
</script>
</body>
</html>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (project not app)
from django.conf import settings
from django.conf.urls.static import static
...
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I found the issue on this problem. If you are trying to use ajax and render a new HTML by simply replacing everything with Jquery like I did ($("*").html(data);).
Be careful about applying CSS on your body element because browsers (as it is said on this post) usually don't care about those tags and remove it.
That's why in my retrieved ajax data, I had the body and everything but when rendered by the browser, the body tag was just disappearing.
If you need to apply CSS tags to body, just add a div tag like this and apply your css on it :
<body>
<div id="body">
....
</div>
</body>
The only weird thing is that when you F5 the page with Django the body tag come back, so the first look was ok but when rendered without refresh no body tag was showing.

static file are not loading in templates django

i am very new to django .
m adding static files but they are not being shown in m templates when i runserver.
if i add an static image the image does not load but only shows a img icon.
#settings.py
STATIC_DIR=os.path.join(BASE_DIR,"static")
STATIC_URL = '/static/'
STATICFILES_DIRS=[
STATIC_DIR,
]
#INDEX.HTML
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>hey eeyone</h1>
<img src="{% static "images/hotel.jpg" %}">
</body>
</html>
You have to add static root in settings.py as -
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
Then create a static folder in app.
In template load static as -
{% load static %}
Add stylesheets href as -
href="{% static 'blog/main.css' %}"

Django- Staticfiles 404 on runserver

I'm not doing anything fancy. Just trying to get my static files to work using python manage.py runserver with Debug = True
'django.contrib.staticfiles' is installed.
These are my static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Here is my template syntax:
{% load staticfiles %}
<title>Dashboard</title>
<!-- Bootstrap Core CSS -->
<link href="{% static "boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css" %}"
rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="{% static "boostrap/bower_components/metisMenu/dist/metisMenu.min.css" %}"
rel="stylesheet">
<!-- Timeline CSS -->
<link href="{% static "boostrap/dist/css/timeline.css" %}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{% static "boostrap/dist/css/sb-admin-2.css" %}" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="{% static "boostrap/bower_components/morrisjs/morris.css" %}" rel="stylesheet">
<!-- Custom Fonts -->
<link href="
{% static "boostrap/bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" type="text/css">
findstatic can successfully locate these files when entered exactly as they are in the template:
(AlmondKing) C:\Projects\AlmondKing>python manage.py findstatic bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css --verbosity 2
Found 'bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css' here:
C:\Projects\AlmondKing\AlmondKing\static\bootstrap\bower_components\bootstrap\dist\css\bootstrap.min.css
Looking in the following locations:
C:\Projects\AlmondKing\AlmondKing\static
C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\contrib\admin\static
My URLS have no conflict:
ROOT URLS:
urlpatterns = [
url(r'^', include('AlmondKing.AKGenius.urls', namespace="AKGenius")),
url(r'^admin/', include(admin.site.urls)),
url(r'^purchases/', include('AlmondKing.InventoryLogs.urls', namespace="purchases")),
url(r'^company/', include('AlmondKing.FinancialLogs.urls',namespace="company")),
]
AKGenius URLS:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name="home"),
url(r'^dashboard/$', TemplateView.as_view(template_name='control_panel.html'), name="dashboard"),
url(r'^support/$', 'AlmondKing.AKGenius.views.support'),
]
and the paths seem to be rendering correctly to the browser:
<!-- Bootstrap Core CSS -->
<link href="/static/boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css"
rel="stylesheet">
And yes, I've restarted runserver since my last settings change.
What could be causing these to 404? Would it have something to do with Windows?
And as a proper answer in case anybody else comes across this post at a later date:
Looks like there's a typo in each line, where
{% static "boostrap
should be
{% static "bootstrap