I have been trying to serve my static files at my Django project, however it cannot find or load it. I have tried different approaches, but none seems to fix the issue.
The static folder is in the same directory as the manage.py.
Also, I have installed the WitheNoise but it also did not solve the problem.
In addition: I am using docker, I have done the collect static and checked the container. All the files are correctly there.
Django version = 2.0.1
Development environment
Code Structure:
Project
- assets
- config
- docs
- project-root
- - static
- - manage.py
- - templates
- - apps
- - project-root
- - - settings.py
- - - urls.py
...
...
setting.py
INSTALLED_APPS = [
'pages.apps.PagesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
html file
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static "css/bootstrap.css" %}">
<link rel="stylesheet" href="{% static "css/jquery.bxslider.css" %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static "css/style.css" %}">
<link rel="stylesheet" href="{% static "css/animate.css" %}">
</head>
Let me know if there is anything else that I need to add to the post that will help you.
Thank you,
The version of Django is not mentioned in the question, also the environment - (production/development)
-In recent versions of python {% load static %} is recommended instead of {% load staticfiles %}
-If Debug is True and if django.contrib.staticfiles is not present in INSTALLED_APP -
-either add django.contrib.staticfiles to INSTALLED_APP
or
append static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns to serve the static files.
Also for static files not in app folders the directory needs to be listed in STATICFILES_DIRS-
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'any_other_locations',
]
Edit your settings.py file and add WhiteNoise to the MIDDLEWARE list. The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
#(Rest of the Middleware here)
]
Routes for the whitenoise cache and static files:
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And run the collectstatic
django-admin collectstatic
or
python3 manage.py collecstatic
If you want to run in inside the docker container, here is more info
https://docs.docker.com/engine/reference/commandline/exec/
More info about Whitenoise:
http://whitenoise.evans.io/en/stable/django.html#
Related
I'm working on a pyhton django project and now I'm trying to add some style to it with a styles.css file but I just can't get it to work.
My project is named commerce and my app is called auctions and I have the static file under
commerce/auctions/static/auctions/styles.css
My settings.py file include
INSTALLED_APPS = [
'auctions',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
My auctions/urls.py
from django.urls import path
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
My styles.css file
h1 {
color: red;
}
Then in my template file, I have this
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Auctions{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'auctions/styles.css' %}">
</head>
<body>
<h1>Auctions</h1>
</body>
</html>
It feels like I'm missing something obvious.
EDIT:
So I managed to fix my issue, and it was the STATIC_URL in my settings.py that was wrong, it looked in the wrong place. I updated it to:
STATIC_URL = 'auctions/static/'
And now it works. Thanks for your replies and help.
Edit your settings.py file and add WhiteNoise (check here the lib) to the MIDDLEWARE list, above all other middleware apart from Django’s SecurityMiddleware:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# ...
]
You should also add this to the settings.py:
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
For more details,check Using WhiteNoise with Django guide.
Addding this in your settings.py should solve the issue:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
The current project I've started working on, uses django 2.2 and most of the links are hardcoded.
All static content is in folder named media and used in base.html as follows
in base.html
{% load staticfiles %} ---- using this as first line of base.html
.......
.......
<head>
<link href="/media/css/backoffice/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
in settings.py
STATIC_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'media'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'media/')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
I've also added following to the main urls.py file:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Yet I'm not able to render the static file listed in the head section of base.html
I've also experimented with commenting out static root and staticfiles_dir but it does not work
You need to put all files in project root's static folder and run this command:
python manage.py collectstatic
For loading static files in the template you need to write this:
{% load static %}
And in all the static files like css, js and images you can do like this:
{% static "<absolute path of file>" %}
And you can refer from documentation.
I hope this will help you!
Using pycharm 2019.2.5,
python 3.7,
Django 2.2.5,
I am creating a website by importing a template and creating apps for it through django, but I can't get any of the static files to work. When I run the dev server, none of the fonts/css/js/images display. Also I can't import google fonts from my HTML file. I've read all the answers and I'm posting the pertinent data i'm aware of. This seems to be a fairly common question, and I've tried all their solutions. Let me know if you need more data.
YSMR *edited to add. #This is my top-level project created in pycharm.
YSMR
\blog
\contact
\schedule
\sendemail
\static
\css # I plan on adding namespacing for this later
\fonts
\js
images....
\templates
\index.html
additional templates...
__init__.py
settings.py
urls.py
views.py
wsgi.py
index.html below. I can view the file, but again, the embedded static files and font do not execute. The first several lines I've loaded below.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>YSMR</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=EB+Garamond:400,400i,500,500i,600,600i,700,700i&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static "css/open-iconic-bootstrap.min.css" %}">
<link rel="stylesheet" href="{% static "css/animate.css" %}">
Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(ENV_PATH, '/static/') #I've tried to change 'static' to something else, but I get an 'unresolved reference' error when I do.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "YSMR/static"), #I get an 'unresolved reference "static"' when I remove the YSMR
]
When I remove the YSMR from the STATICFILES_DIRS path, I get an "unresolved reference 'static'" warning
also, django.contrib.staticfiles is included in INSTALLED_APPS
Thanks in advance.
Change your settings as follows and try:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn")
Also make sure that you added these lines to your main url file.
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change your settings as follows and try:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "app_name/static_root"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "app_name/static")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
Also make sure that you added these lines to your main url file.
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I tried fetching static files for my website but nothing seems to work even the other stackoverflow answers.
please help on this.
settings.py -
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
File is present in :
parent_folder>static>static_dirs>css>cover.css
HTML
<html lang="en">
{% load staticfiles %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Aman Turate">
<title>Aman Turate - Resume</title>
<link rel="stylesheet" href="{% static 'css/cover.css' %}">
This works for me. Update your settings.py to this
.........
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
.........
Make sure the static folder is in the root (i.e where manage.py is)
There are several things to consider here and I am not sure which applies because I'm working on pure assumptions of your situation without knowing:
What is BASE_DIR set to
Have you run manage.py collectstatic
what is your server setup or are you just working off the django development server?
Where are the files you're trying to link to actually placed
Anyway here is some info I hope will be useful. I will break down how the settings files relates to your template file and hopefully that will help you debug your problem.
STATIC_URL = '/static/' -- > the value of this is what will be appended to the static file you are linking in your template. It is the relative url after your domain name. So {% static 'css/styles.css' %} will be rendered as /static/css/styles.css in your html page when it is loaded.
STATIC_ROOT is the absolute path of where your files are located on disk. It tells django where to place all static files collected from your apps when you run manage.py collectstatic see here for details.
STATICFILES_DIRS tells django where to find project static files. By default Django will look for a static directory in each registered app and collect the files in there and place then in your STATIC_ROOT folder. If you want to put static files in a different directory in your project and you want django to know about it then you list those paths in this config variable.
With your code:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
{% static 'css/cover.css' %} is translating to /static/css/cover.css, your telling django the root directory to collect static files is <your BASE_DIR>/static/static_root so here you can see that there might be a miss match in locations. Again I don't know if you ran collectstatic. your STATICFILES_DIR is just going to look for static files in <your BASE_DIR>/static/static_root to then put them in <your BASE_DIR>/static/static_root ... if that makes sense.
I'm a beginner in using django and tryin to make my first app, but I keep on getting "Not found" every time I add a javascript file on my view
This is my setting.py
STATIC_URL = '/home/me/PycharmProjects/GLife/static/'
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
)
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^register', include('register.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--<script src="/static/djangular/js/django-angular.min.js" type="text/javascript"></script>-->
<script src="{% static '/js/_register/register.js' %}" type="text/javascript"></script>
<title></title>
</head>
<body>
I've already search about it but the suggestions failed, hope anyone could help
here's my project structure
myproject
--main
--register
---migrations
---templates
--static
---js
----_register
I'm just trying to make an alert display as a testing using js
This is happening because you switched the values of STATIC_ROOT and STATIC_URL. It must be like this:
STATIC_URL = '/static/'
STATIC_ROOT = '/home/me/PycharmProjects/GLife/static/'
STATIC_URL is the URL to use when referring to static files located in STATIC_ROOT.
STATIC_ROOT is the absolute path to the directory where collectstatic will collect static files for deployment.
Also, your static and STATIC_ROOT paths must be different.
When using the development server you don't need to configure STATIC_ROOT or use collectstatic management command because it will automatically serve the static files from static folder if DEBUG is true.