Static files don't load in django framework - django

django don't load static files, on the site when i use f12 i can see that /static/js/.., but styles not work
Template home-page.html
{% load static %}
piece of code and
<!-- JQuery -->
<script type="text/javascript" src="{% static 'app1/js/jquery-3.4.1.min.js' %}"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'app1/js/popper.min.js' %}"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'app1/js/bootstrap.min.js' %}"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static '../js/mdb.min.js' %}"></script>
<!-- Initializations -->
<script type="text/javascript">
// Animations initialization
new WOW().init();
urls.py
from commercemag import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app1.urls', namespace='item-list')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
it's settings
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
idk what i should do, please help me

add this in your code
import os
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]

try to add this in urls.py but this is only work when we posting any images from templates and stored in static files
urlpatterns = [
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
also try this
comment your STATIC_ROOT = os.path.join(BASE_DIR, 'static')

update settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'static')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Related

Can't link my css file in my django project

index.html
{% 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" href="{% static 'style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
settings.py (my app name is base)
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'testpro.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'testpro.wsgi.application'
...
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Folder structure is like this:
project folder
/static
/style.css
CSS contains a simple color change and it is not working.
I've tried linking the css file in different ways and nothing seems to be working. I don't know how or why but sometimes it suddenly works and then suddenly stops working.
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Try this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
You don't need to specify base directory in templates array.
DIRS': [BASE_DIR, 'templates'],
Just let it be empty.
DIRS': [],
and all other looks fine just make sure about CSS files. and it's location.
add this to the
<head>
<link href="{%static 'style.css'%}" rel="stylesheet">
</head>
and
add this to the testpro (urls.py)
from testpro import settings
urlpatterns = [
// here goes your urls
]
//at the bottom add this
urlpatterns += static(settings.STATIC_URL , document_root=settings.STATICFILES_DIRS)
and in the settings.py
change
STATICFILES_DIRS= BASE_DIR, 'static' to
STATIC_ROOT = os.path.join(BASE_DIR,'static')
Change this part of the settings.py to something like this:
STATIC_URL = 'static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, '<Your APP name goes here>\static'),)
If you have an 'css' subfolder inside your static folder then you need to add that to the relative path in your HTML template like this:
{% 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" href="{% static 'css/style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
I hope that helps you!

404 for static images and media in Django in Production Mode

I am beginner in Django
I am trying to run my application on Debug=False mode to simulate the production environment, I have added all the static url, and roots. My program is generating the static images in real-time from the video passed to the application during runtime.
This is working as expected in the development mode but I am getting 404 for images and videos in the production mode other stuff like bootstrap and JS are getting loaded fine.
Earlier bootstrap and js was also not loading then I installed Whitenose and things start working, but now images and videos and giving 404.
Link to the application code: https://github.com/abhijitjadhav1998/Deepfake_detection_using_deep_learning/tree/master/Django%20Application
Further to this application, I have added the STATIC_ROOT in the settings.py
and added os.system('python manage.py collectstatic --noinput')
in the views.py folder to populate the static path with images and videos before sending the response to the html page.
But still I am getting the 404, I also checked the file with same name is avaliable in the location.
I am getting the below error:
Error from the console: Able to load the js, bootstrap but able to load the images and video
Code from settings.py that I have added
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
"whitenoise.runserver_nostatic",
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ml_app.apps.MlAppConfig',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'project_settings.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media'
],
},
},
]
WSGI_APPLICATION = 'project_settings.wsgi.application'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(PROJECT_DIR, 'db.sqlite3'),
}
}
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'models')
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static'),
os.path.join(PROJECT_DIR, 'models'),
]
STATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles')
CONTENT_TYPES = ['video']
MAX_UPLOAD_SIZE = "104857600"
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'uploaded_videos')
EDIT :
I added all the uploaded_images into static/images/uploaded_images, this is loading the static images but now the issue is it is not loading the images from a for loop in html file
For below the images gets loaded as expected.
<div id="preprocessed_images" class="col-12 mt-4 mb-2">
{% for each_image in preprocessed_images %}
<img src="{%static 'images/uploaded_images/uploaded_file_1651078566_cropped_faces_5.png'%}" class="preprocess"
width=auto height="250" />
{%endfor%}
</div>
For below it is still giving 404. the value of each image is each_image = images/uploaded_images/uploaded_file_1651078566_cropped_faces_5.png
<div id="preprocessed_images" class="col-12 mt-4 mb-2">
{% for each_image in preprocessed_images %}
<img src="{%static each_image%}" class="preprocess" width=auto height="250" />
{%endfor%}
</div>
I am loading meadia files like this but still its 404
<video height="320" width="640" id="predict-media" controls>
<source src="{{MEDIA_URL}}{{original_video}}" type="video/mp4" codecs="avc1.4d002a" />
</video>
I think the problem is here:
<div id="preprocessed_images" class="col-12 mt-4 mb-2">
{% for each_image in preprocessed_images %}
<img src="{% static each_image %}" class="preprocess" width=auto height="250" />
{%endfor%}
You don't need the word static in there, instead do this:
<img src="{{ each_image.url }}" class="preprocess" width=auto height="250" />
Django doesn't serve static files in production automatically we will need a web server like apache/Nginx to serve the static files.
I was able to serve the static files by hosting the application on Nginx as a reverse proxy server and Gunicorn to handle Django requests. I used docker to host the application.
Step by step guide is given in this Blog

Using an django-sass-processor library in django but refuses to apply the style because its MIME type is not a supported stylesheet

I'm using Sass for my Django(3.2.6) website with the help of libraries called django-compressor and django-sass-processor to compile it to a .css file. It works fine during development but when I try to disable the DEBUG mode in the settings the error will pop-up.
Refused to apply style from 'http://127.0.0.1:8000/static/styles.css'
because its MIME type ('text/html') is not a supported stylesheet MIME
type, and strict MIME checking is enabled.
Setting up the library I've added the following code to my settings.py (between ---- lines):
# Application definition
INSTALLED_APPS = [
--------------------------------------------------------------------
'sass_processor',
--------------------------------------------------------------------
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'openfiles.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('templates'))],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'openfiles.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Manila'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
------------------------------------------------------------------------
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
SASS_PROCESSOR_ROOT = STATIC_ROOT
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'sass_processor.finders.CssFinder',
]
-------------------------------------------------------------------------------
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Here are my static directory files structure BEFORE running library:
.
├── public (folder for images)
├── _scss (folder for .scss files)
└── styles.scss
AFTER running library, it created two files called styles.css.map and styles.css:
.
├── public
├── _scss
├── styles.css
├── styles.css.map
└── styles.scss
To access scss tags, HTML now use {% load scss_tags %} tag, here is my head.html:
{% load sass_tags %}
<head>
<meta charset="UTF-8">
<link href="http://gmpg.org/xfn/11" rel="profile">
<link type="text/plain" rel="author" href="{% url 'index' %}/humans.txt">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta property="og:title" content="{{ site_title }}">
<meta property="og:site_name" content="{{ site_brand_name }}">
<meta property="og:url" content="{% url 'index'} %">
<meta property="og:description" content="{{ site_description }}">
<meta property="og:type" content="website">
<meta property="og:image" content="{% sass_src 'public/meta-img.png' %}">
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v2.0.1/css/unicons.css">
<title>
{% block title %}
Open Siena Files
{% endblock title %}
</title>
<!-- CSS -->
<link type="text/css" rel="stylesheet" href="{% sass_src 'styles.scss' %}" >
<!-- Icons -->
<link rel="shortcut icon" href="{% sass_src 'public/favicon.ico' %}">
</head>
But when running it without DEBUG mode the browser produces the error. YES YES YES. I already search for a solution but nothing seems to fit with specific problem I have about library converting scss to css.

Why brower is not loading static files?

settings.py
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static_in_env')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
MEDIA_URL = '/media/'
django.contrib.staticfiles' included in installed_apps. {% load static from staticfiles %} used in base.html.
still getting these errors:
[22/Dec/2019 13:45:31] "GET / HTTP/1.1" 200 10735
[22/Dec/2019 13:45:32] "GET /static/js/jquery-3.4.1.min.js HTTP/1.1" 404
1791
[22/Dec/2019 13:45:43] "GET /static/css/bootstrap.min.css HTTP/1.1" 404
1788
[22/Dec/2019 13:45:43] "GET /static/css/mdb.min.css HTTP/1.1" 404 1770
......
script.html
{% load static from staticfiles %}
<script type="text/javascript" src="{% static 'js/jquery-3.4.1.min.js'
%}">
</script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}">
</script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}">
</script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}">
</script>
<!-- Initializations -->
<script type="text/javascript">
// Animations initialization
new WOW().init();
</script>
staticfiles dir includes following files and folders
static_in_env
- css
-bootstrap.css
-bootstrap.min.css
-mdb.css
-mdb.min.css
-mdb.lite.css
-mdb.lite.min.css
-style.css
-style.min.css
- font
- img
- js
-bootstrap.js
-bootstrap.min.js
-mdb.js
-mdb.min.js
-popper.min.js
- scss
In your project_name/urls.py, try to add the following at the end:
urlpatterns = [
# your urls...
]
# ↓ add this ↓
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also, just put {% load static %} in your script.html, not {% load static from staticfiles %}
In settings.py add
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
In base.html
{% load static %}
Hopefully it will work if it doesn't run this command
Python manage.py collectstatic
if you are using bootstap, either you download it or use cdn
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
or you can use the starter template provided by bootstrap, which will have all the basic html,css and js files. Link: https://getbootstrap.com/docs/4.4/getting-started/introduction/
custom css links can be linked to the file as follows
<link rel="stylesheet" type="text/css" href="{% static 'css/custom.css' %}"/>

cannot loading custom CSS in Django ontop of Bootstrap

I am able to load my static images, however; when it comes to loading my custom css sheets I cannot seem to get it working.
Because my static images are loading, I believe that my settings.py is set up properly, however, I could be wrong.
My static files for css and images are located within /static/img/hive.png and /static/css/main.css respectively.
Any help is greatly appreciated!
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ALLOWED_HOSTS = []
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ideas.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ideas.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
home.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<!-- personal css -->
<link rel="stylesheet" href="{% static "css/main.css" %}">
</head>
<body>
<img src="{% static "img/hive.png" %}" alt="My image"/>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
</html>
Had to run 'python manage.py collectstatic' for my static files to update.