static dir not found django - python

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.

Related

Django not able to load a simple static page with static files

It is a simple static html file with only one image as a static file in the html. I have followed all the steps provided in the Django documentation, and the collectstatic command runs without any error.
The project folder structure is as follows;
settings.py file;
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
DEBUG = True
home.html - File where the image is not loading;
{%load static%}
<!DOCTYPE html>
<html >
<head>
<title>home.html</title>
<h1>This is a test file</h1>
</head>
<body>
<img src="{% static 'images/test.png' %}">
</body>
</html>
Output:
I have tried the following;
Restart server,
rerun the collectstatic command
Nothing worked out, What could be the issue? Please help me to resolve this issue.
replace STATICFILES_DIR with STATICFILES_DIRS in settings.py
You have STATIC_ROOT = os.path.join(BASE_DIR, 'assets') whereas it looks like you've already collected your files to os.path.join(BASE_DIR, 'static'), which is a more typical location. You should change STATIC_ROOT to point back to the static folder so that Django knows where to serve those files from:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
You can see this in the static files deployment guide
try this in your settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
def get_success_url(self, request, user):
return (get_success_url)
and add this from your urls.py
urlpatterns = [
......
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
STATICFILES_DIR is the main error here.
Replace it with STATICFILES_DIRS
This should solve it.

Unable to display static images and load CSS in Django

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)

Serving Static File on Django

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#

static files not found error in django

I know that this problem has already been asked several times here. I have searched and read a number of answers but no help. I guess, I am missing something very basic.
In my settings.py, I have:
STATIC_URL = '/static/'
STATIC_ROOT = join(APPS_DIR, "static/")
# STATICFILES_DIRS = [join(APPS_DIR, 'static')]
MEDIA_ROOT = join(APPS_DIR, 'media')
MEDIA_URL = "/media/"
In my config/urls.py, I have:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have a file located at /static/core/js/jquery_countdown/jquery.countdown.min.js which I am trying to load in template as below:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'core/js/jquery_countdown/jquery.countdown.min.js' %}"> </script>
The top of the same template looks like
{% extends "contest/base.html" %}
{% load static %}
This results in following server error:
[23/Mar/2018 10:12:08] "GET /static/core/js/jquery_countdown/jquery.countdown.min.js HTTP/1.1" 404 1858
What am I missing?
Create folder static_files in your app directory. And place all your static files inside it. Then use the following settings
STATIC_URL = '/static/'
STATIC_ROOT = join(APPS_DIR, "static/")
STATICFILES_DIRS = [join(APPS_DIR, 'static_files')]
If it does not solve your issue, then run the command python manage.py collectstatic. It will copy all the static files (Not only from your app but also from django admin, third party apps etc) to the STATIC_ROOT folder.
Details
For local serving, django server will look in to the STATICFILES_DIRS. So you dont need to run the python manage.py collectstatic command. All the external apps may have STATICFILES_DIRS where they place their static files. For production server you need to collect all these static files scattered around all your apps in to a single place. Thats what python manage.py collectstatic command will do. It will copy all the static files in to STATIC_ROOT directory
You are searching for static files in app directories only but have your file in global static files. You should use the commented STATICFILES_DIRS setting to specify all places to search for static files.
I found that this worked for me. (Development)
(I chose to name it "zStatic" to keep it at the bottom of the root (project folder), so that it isnt amidst all my apps. Easier to locate.)
Settings.py
STATIC_URL = 'zStatic/'
STATICFILES_DIRS = (
BASE_DIR/'zStatic',
)
INSTALLED_APPS =
[
...
'django.contrib.staticfiles',
...
]
base.html (base template)
<head>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/mycss.css' %}">
</head>

Django -- Can't get static CSS files to load

I'm running Django's development server (runserver) on my local machine (Mac OS X) and cannot get the CSS files to load.
Here are the relevant entries in settings.py:
STATIC_ROOT = '/Users/username/Projects/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/Users/thaymore/Projects/mysite/cal/static',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
# other apps ...
'django.contrib.staticfiles',
)
In my views.py I'm requesting the context:
return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request))
And in my template the {{ STATIC_URL }} renders correctly:
<link type="text/css" href="{{ STATIC_URL }}css/main.css" />
Turns into:
<link type="text/css" href="/static/css/main.css"/>
Which is where the file is actually located. I also ran collectstatic to make sure all the files were collected.
I also have the following lines in my urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
I'm new to Django so am probably missing something simple -- would appreciate any help.
Read this carefully:
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
Is django.contrib.staticfiles in your INSTALLED_APPS in settings.py?
Is DEBUG=False? If so, you need to call runserver with the --insecure parameter:
python manage.py runserver --insecure
collectstatic has no bearing on serving files via the development server. It is for collecting the static files in one location STATIC_ROOT for your web server to find them. In fact, running collectstatic with your STATIC_ROOT set to a path in STATICFILES_DIRS is a bad idea. You should double-check to make sure your CSS files even exist now.
For recent releases of Django, You have to configure static files in settings.py as,
STATIC_URL = '/static/' # the path in url
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
and use it with static template tag,
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
Another simple thing to try is to stop, and then restart the server e.g.
$ python manage.py runserver
I looked into the other answers, but restarting the server worked for me.
Are these missing from your settings.py? I am pasting one of my project's settings:
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")
Also, this is what I have in my urls.py:
urlpatterns += patterns('', (
r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': 'static'}
))
added
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), )
and removed STATIC_ROOT from settings.py, It worked for me
Add the following code to your settings.py:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
After that, create the static folder at the root directory of your project.
To load the static files on templates use:
{% load static %}
<img src="{% static "images/index.jpeg" %}" alt="My image"/>
DEBUG = True in my local settings did it for me.
These steps work for me, just see Load Static Files (CSS, JS, & Images) in Django
I use Django 1.10.
create a folder static on the same level of settings.py, my settings.py's path is ~/djcode/mysite/mysite/settings.py, so this dir is ~/djcode/mysite/mysite/static/;
create two folders static_dirs and static_root in static, that's ~/djcode/mysite/mysite/static/static_dirs/ and ~/djcode/mysite/mysite/static/static_root/;
write settings.py like this:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'mysite', 'static', 'static_dirs'),
)
do this command $ python manage.py collectstatic in shell;
create a folder css in static_dirs and put into your own .css file, your css file' path is ~/djcode/mysite/mysite/static/static_dirs/css/my_style.css;
change <link> tag in .html file: <link rel="stylesheet" type="text/css" href="{% static 'css/my_style.css' %}">,
Finally this link's path is http://192.168.1.100:8023/static/css/my_style.css
Bingo!
You had same path in STATICFILES_DIRS AND STATIC_ROOT, I ran into the same issue and below was the exception -
ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
For local you don't need STATICFILES_DIRS, as anyway you don't need to run collectstatic. Once you comment it, it should work fine.
Have you added into your templates:
{% load staticfiles %}
This loads what's needed, but for some reason I have experienced that sometimes work without this... ???
I had to use
STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', )
That helped me.
See if your main application (where the static directory is located) is included in your INSTALLED_APPS.
Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.
I tried this model and it worked.
Changes in settings as per the django project created with shell
"django-admin.py startproject xxx"# here xxx is my app name
modify the folder as below structure loading our static files to run on server
Structure of xxx is:
> .
> |-- manage.py
> |-- templates
> | `-- home.html
> `-- test_project
> |-- __init__.py
> |-- settings.py
> |-- static
> | |-- images
> | | `-- 01.jpg
> | |-- style.css
> |-- urls.py
> `-- wsgi.py
- modifications in Settings.py
import os
INSTALLED_APPS = ( 'xxx',# my app is to be load into it)
STATIC_ROOT = ''
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, '../templates'),)#include this
- modifications in urls.py
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class DirectTemplateView(TemplateView):
extra_context = None
def get_context_data(self, **kwargs):
context = super(self.__class__, self).get_context_data(**kwargs)
if self.extra_context is not None:
for key, value in self.extra_context.items():
if callable(value):
context[key] = value()
else:
context[key] = value
return context
urlpatterns = patterns('',
url(r'^$', DirectTemplateView.as_view(template_name="home.html")), )
- home.html
<html>
<head>
<link href="{{STATIC_URL}}style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>This is home for some_app</h1>
<img src="{{STATIC_URL}}/images/01.jpg" width=150px;height=150px; alt="Smiley ">
</body>
</html>
Add this "django.core.context_processors.static", context processor in your settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.static",
)
You can just set STATIC_ROOT depending on whether you are running on your localhost or on your server. To identify that, refer to this post.
And you can rewrite you STATIC_ROOT configuration as:
import sys
if 'runserver' in sys.argv:
STATIC_ROOT = ''
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
If you set DEBUG=FALSE
you need to do follow steps
In your urls.py file:
add this line
from django.views.static import serve
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
I have the same issue (ununtu 16.04 server).
This helped me
python manage.py collectstatic --noinput
add following in settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Two most Basis points to be noted for running Static files in Django Application are - Declare static file path in your settings.py file
STATIC_URL = '/static/'
Another important parameter is the web page in which you are using static keyword, you need to load the static files.
{% load static %}
Go to your HTML page load static by
{% load static %}
Now only mistake I've made was this
My code:
<img src="**{% static** "images/index.jpeg" %}" alt="My image">
Updated:
<img src=**"{% static 'images/index.jpeg' %}' alt="My image"**>
You get it right
I had same issue check your settings.py and make sure STATIC_URL = '/static/'
in my case first / at the beginning was missing and that was causing all static files not to work

Categories

Resources