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

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

Related

Django static files not working in localhost

I have my Django app running on a development server. The HTML templates are serving fine but I'm really having a lot of trouble getting the static files to serve. I've tried lots of ideas from Stack Overflow but not getting anywhere.
I just get a 404 error on the image.
Can anyone help me please?
My urls.py is:
from django.contrib import admin
from django.urls import path
from app import views
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# The rest of my urls here...
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
my settings has included:
STATIC_ROOT = "/home/me/django-test/djangoproject/static"
STATIC_URL = 'static/'
and my template has:
<!doctype html>
{% load static %}
<img src="{% static 'e.png'%}">
It worked for me in django 3.2.
For local static you should create folder called "static" in your config folder
config it's folder created when you start project(may be you call it mysite or smth):
django-admin startproject config
create a "static" folder in the same folder where you have the file settings.py
#In settings.py:
STATIC_URL = '/static/'
# folder for static when you deploy your project on server(not for local develop)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# local (in config for runserver)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "config/static"),
]
Inside folder "static" place your css, js, img e.t.c folders
In our templates you have to do something like this:
<!DOCTYPE html>
{% load static %}
<html lang="ru">
<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" href="{% static 'css_custom/base_style.css' %}"/>
<title>{% block title %}TITLE{% endblock title %}</title>
</head>
Pay attention to my template tag
href="{% static 'css_custom/base_style.css' %}"
that means i load static from:
config/static/css_custom/base_style.css
Same thing for load image, in you template.html:
{% extends '_base.html' %}
{% load static %}
{% block content %}
<img src="{% static 'images/Bg.jpg' %}" alt="">
{% endblock content %}
that means static from:
config/static/images/Bg.jpg
or you can add relative path into your style.css for some classes like:
.header-home {
height: 40vh;
background-image: url("../images/Bg.jpg");
background-size: cover;
background-position: center;
text-align: center;
}
Hope it helps you

Django static files on AWS S3 Bucket

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>

why are my static files not getting detected in django?

I want to add a static file to my django project app.
My app is named "core"
Hence inside the app where I need the static file (called main.css) , I made a directory named static/core/main.css
So after that my directory looks like this
core
....
-static
|_core
|_main.css
.........
And in the settings.py file , I wrote this
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
And in the html file where I want the static css I wrote this
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %} Welcome | Ecommerce {% endblock %}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
<link rel="stylesheet" href="{% static 'core/main.css' %}">
This HTML file is located in a global project level template folder where I dump the templates from all the apps in the project .
But my static file is not getting loaded for some reason
May be because you didn't specify the file?
I guess you should change it from
<link rel="stylesheet" href="{% static '' %}">
To
<link rel="stylesheet" href="{% static 'core/main.css' %}">
Try to add
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
into your Django settings
In Your settings.py file add this
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
after that open the terminal in your root directory and run the following command
python manage.py collectstatic
you can also refer to the django documentation where they have explained about staticfiles in django https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/

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'), ]

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' %}"