Django : cannot find the static files - django

In my Django project, the settings are the following ones:
A settings folder, including a base.py and a production.py files.
The base folder defines a path taking into account this tree:
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(
os.path.join(__file__, os.pardir))))
And the static is defined as such:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
When I launch collectstatic the static folder is mounted at the root of the project, as planned.
However, the static files are not found neither by the html pages, although configured as seach:
{% load static %}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'style_sheet.css' %}">
<title>{% block title %}Advocacy Project{% endblock %}</title>
</head>
and when I check with findstatic, it looks like it does not look into the right folders:
python manage.py findstatic style_sheet.css --settings my_project.settings.production --verbosity 2
No matching file found for 'style_sheet.css'.
Looking in the following locations:
/Users/my_name/Documents/my_project/venv/lib/python3.7/site-packages/django/contrib/admin/static
My question is: How could I make Django check in the right folders ?

Thanks ASFAW AYALKIBET support here is a detailed process to install Whitenoise on Django with multiple settings.
Install Whitenoise pip install Whitenoise
Create settings folder in the project folder.
Add base.py and production.py along with the __init__.py file in this folder.
in production.py add
DEBUG = False
In the settings, amend BASE_DIR as such :
BASE_DIR = Path(__file__).resolve().parent.parent.parent
insert 'whitenoise.runserver_nostatic'in INSTALLED_APPS and 'whitenoise.middleware.WhiteNoiseMiddleware' in MIDDLEWARE,(cf whitenoise official doc).
Again in the settings, add STATIC_ROOT = BASE_DIR / 'staticfiles'
In wsgi.py amend the settings path:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.production')
then you can collect the static files using:
python manage.py collectstatic --settings settings.my_project.production
Launch the servers:
gunicorn my_project.wsgi to check the production mode
python manage.py runserver --settings settings.my_project.base to use the debug mode.

First check if debug = False or True in your setting. Django will not host your static files in Debug = False mode. You have to use something like whitenoise to host you static files in production.

Related

Styles not loading in Django

I have a site that needs some custom styles in Django and I can't get the static file to load.
I have a static folder inside my main folder - The one where manage.py lives, Inside there is a CSS folder that contains a style.css.
At the top of base.html, I load
{% load static %}
Then in the head of my HTML I load
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
and in my settings.py file I have loaded in
# Static file route
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
When I load I just get a blank CSS file and no styles load, I'm fairly new to Django so please be kind, and thanks in advance.
Also, I want make sure my static folder is created in the right place:
Try
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
where BASE_DIR = Path(__file__).resolve().parent.parent
check also that you have
INSTALLED_APPS = [
'django.contrib.staticfiles',
]
From your screen your static is css/style.css but you load <link rel="stylesheet" href="{% static 'css/styles.css' %}"> instead.
You need to load <link rel="stylesheet" href="{% static 'css/style.css' %}">
You have to run in terminal:
python manage.py collectstatic
After every change of static files if I remember correctly.
Other then that, pressing F12 in a browser can show why a specific file isn't loading. So can the terminal/console where Django is running(or log files if no access to it).

Why can't I serve my static files to Django?

Before anyone marks this as a duplicate I have seen all of the other questions on similar topics and tried all of the solutions without effect.
My Django application is small and I am happy to serve the static files from the same server
In settings.py I have
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I have uploaded my application to the server and run
python.manage.py collectstatic
All of my static files are in the appropriate directories under staticfiles
project-root
├── staticfiles
│   ├── css
│   │   ├── base.css
│   ├── js
│   │   ├── common.js
In my html I have
{% load static %}
<link href="{% static 'css/base.css' %}" rel="stylesheet">
On loading the page I get the error
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I think this is because it cannot find the css file
Where am I going wrong? Do I need to provide any more information?
project_name - app_name - static - app_name - css/js file
<link rel="stylesheet" href="{% static 'app_name/style.css' %}">
My problem has been solved by installing the whitenoise package. (I have not seen this recommended on the responses to similar questions around this problem)
pip install whitenoise
And add it to the middleware section of settings.py
MIDDLEWARE = [
...
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
All of my static files are now loaded and the site works perfectly with no further configuration
(I am assuming that the problem might have been caused by a quirk in the site's host's server settings.)

Staticfiles in Django coming from npm-run-build frontend throw Error 404

I want to add my Gatsby JS' public folder that I created with npm run build to be served to Django as_view. Django keeps throwing 404 Error at me when I'm trying to load the staticfiles and the index.html from STATICFILES_DIRS.
I don't understand how Django is not able to find the JSON file e.g /app-data.json even if I provide an absolute path.
Note: I tried python3 manage.py runserver --insecure (and without insecure as well) - didn't work.
Directory structure:
./frontend
- ./public
- ./codeblock
- ./codeblock/1-index
- ./staticfiles
- ./staticfiles/d
- ./page-data
- /app-data.json
- ./index.html
- ...
./backend
- ./backend
- settings.py
package.json
"scripts": {
"start": "gatsby develop",
"build": "gatsby build --prefix-paths",
"format": "prettier --write \"src/**/*.{js,jsx,css,json}\"",
"lint": "eslint --fix \"src/**/*.{js,jsx}\""
},
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
BACKEND_DIR = BASE_DIR
FRONTEND_DIR = os.path.abspath(
os.path.join(BACKEND_DIR, '..', 'frontend'))
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(FRONTEND_DIR, 'public'),
os.path.join(FRONTEND_DIR, 'public', 'page-data'),
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
...imports
urlpatterns = [
url('test/', views.FrontendAppView.as_view()),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
index.html
In the HTML file if I define the path with /static/, such as href="/static/webpack-runtime-4145e7520a88c179d990.js", then Django can pull in the JS static files, otherwise 404 Error.
<!DOCTYPE html>
<html lang="en">
<head>
<link as="script" rel="preload" href="webpack-runtime-4145e7520a88c179d990.js" />
<link as="script" rel="preload" href="commons-926e13980b7ff3c9526c.js" />
<link as="script" rel="preload" href="app-425daa4026ff9a50d14f.js" />
<link as="fetch" rel="preload" href="page-data/index/page-data.json" />
</head>
...
to serve static files you need to differentiate between development (Debug = True) and production (debug = False) modes:
If you are in a development Mode : (debug = True):
https://docs.djangoproject.com/en/3.0/howto/static-files/#managing-static-files-e-g-images-javascript-css
If you are in a production Mode : (debug = False):
https://docs.djangoproject.com/en/3.0/howto/static-files/deployment/#serving-static-files-in-production
You can use Django Whitenoise to serve static files in Production
If anyone is interested, here's what solved this issue for me.
Issue 1: I didn't add {% static %} and {% load static %}
Issue 2: I had to make changes after npm run build each time in the HTML file
Solution: If you are using Gatsby JS, edit your congif.js as seen below. It will add /static/ before the path and Django will be able to render your pages correctly. This way you don't have to add {% static %} and {% load static %}:
const config = {
gatsby: {
pathPrefix: '/static/'
}

Django serving static files locally

It's been a while since I've setup django to work locally. I'm using version 1.11. Getting it to serve the static files.
My project is called chatsys and I've created the static folder and css in this folder chatsys\static\css\style.css .
Here's the current settings in the settings file.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
and in the urls
#for serving static files
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and finally in the html
{% load static %}
...
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
however in the runserver console I get 404 for /static/css/style.css
You should define STATICFILES_DIRS and include your project's static directory there.
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
These are the directories that Django collects static files from.
You should then change STATIC_ROOT to be a different directory. It is the directory that collectstatic collects static files to. The static root should not be under version control.
As an aside, you are loading the static tag in your template but not using it. You could change it to:
{% load static %}
...
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
Move your static folder under the base dir
chatsys
migrations
templates
etc.
static
css
style.css

how to point correctly to static image in django

I have a template that renders an image:
{% load staticfiles %}
<img src="{% static "img/logo.png" %}" alt="My image"/>
The image link is broken, but it points to:
localhost/static/img/logo.png
What are values I need to set for static_root, static_url, and STATICFILES_DIRS to get this image to show up correctly?
This is my directory structure:
myprojectname (top level)
--- myprojectname
--- --- myproectname
--- --- --- settings
--- --- --- --- base.py (setting.py)
--- --- static
--- --- --- img
This is my static configuration in settings:
STATIC_ROOT = '/Users/myuser/myprojectname/myprojectname'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
#normpath(join(SITE_ROOT, 'static')),
os.path.join(BASE_DIR, "static"),
'/Users/myuser/myprojectname/myprojectname/static',
)
This is what it shows:
I have already done a collectstatic and this doesn't work.
Static files can be confusing in Django. I'll try to explain as simply as possible...
STATIC_ROOT
This is the directory that you should serve static files from in production.
STATICFILES_DIRS
This is the directory that you should serve static files from in development.
STATIC_ROOT and STATICFILES_DIRS cannot point to the same directory.
Django is a highly modular framework. Some application modules contain their own templates, css, images and JavaScript. Django admin is one such app. Django extends this modularity to applications you create by using different directories for static files in development versus production.
When DEBUG = True and you have included django.core.staticfiles in your INSTALLED_APPS, Django will serve the files located in the STATICFILES_DIRS tuple using the STATIC_URL path as the starting point.
In production this responsibility should be given to Nginx, Apache, CloudFront, etc. When DEBUG = False, Django will not automatically serve any static files.
When you run:
$ python manage.py collectstatic
The files specified in the STATICFILES_DIRS are copied into the STATIC_ROOT to be deployed.
So, to answer your question, I would do the following:
Create another directory to store your static files in development and add that path to your STATICFILES_DIRS. I usually call this folder "static-assets". It can reside at the same level as your existing "static" directory.
Set STATIC_ROOT to the path to your existing "static" directory.
If you look closely at the path that's returning a 404 in your screenshot, the image path is specified as: /static/img/logo.png, but your directory for images is: /static/image/
So double-check your image path to make sure you're pointing to the right directory.
Make folder "staticfiles" in root of your project where settings.py exists
In staticfiles you can go this way..
css
js
images
In settings.py
STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR,'staticfiles'), # if your static files folder is named "staticfiles"
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR,'template'), # if your static files folder is named "template"
)
In base.html
<link rel="stylesheet" type="text/css" href="{% static 'css/demo.css' %}" />
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
In other template files in which you include base.html
{% extends "base.html" %}
{% load static %}
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<div id="yourID" class="yourClass">
<img src="{% static "images/something.gif" %}" alt="something" >
</div>
If you are in development mode then define just one line:
STATICFILES_DIRS = ( os.path.join('static'), )
You don't need to define STATIC_ROOT = '/Users/myuser/myprojectname/myprojectname'
OR
STATICFILES_DIRS as BASE_DIR
So, working solution is :
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('static'), )
actually I too was struggling with the same problem , it got resolved now , check javapoint documentation once its really good , another method that worked for me is change the path of static folder i.e place the static folder inside the app folder that u have created (in my case , the static folder is inside the first_app folder) . it should work . after that I relocated my folders back to where it was and to my surprise , it worked again!. sometimes it may be the fault of browser . I tried my level best to explain as I am a beginner in Django .
If you want to save static files in Django you will need to do the following
in settings.py file you will have something like this `
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'my_project/static') # where I want to host the static files i.e img, js & css
]
depends on how you have structure you files but you will need to have something like this in your urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', include('appfront.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Final your template will have something like this Note the usage of static tag
{% load static %}
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
<div class="container">
<a class="navbar-brand" href="{% url 'index' %}">
<img src="{% static 'img/logo.png' %}" class="logo" alt="">
</a>
'''