404 error when getting file in static, django - python

I tried several attempts through googling, but it didn't work. I don't think it was like this when I was working on another Jango project, but I don't know why.
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.HomeView.as_view(), name = 'home'), #to home.html
path("blog/", include('blog.urls')),
]
# urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),)
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static")
home.html
<img src="{% static 'assets/img/navbar-logo.svg' %}" alt="..." />
directory
Project-folder
|
|__config
| |__settings.py
| |__urls.py
|
|__app
|
|__template
| |__app
| | |__bla.html
| |__home.html
|
| #bootstrap
|__static
|__assets
|__img
...

An Excerpt from the docs.
Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.
So, use list of dictionaries and also it is STATICFILES_DIRS not STATICFILES_DIR, you missed S.
Try this:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
Or this:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Make sure that you have loaded the static tag using % load static %.

If you've didn't loaded the static try this in your base.html or the home.html
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">

Related

Why isn't my picture loading from my static folder?

I am working with the Django framework and am having some problems with referencing the source of an image from my HTML page. I continuously get this error in my terminal
Not Found: /bread.jpg
"GET /bread.jpg HTTP/1.1" 404 2445
although the last 4 digit string is different with every attempt I make to fix it.
My project (YeOldeShoppe) has an app (Shoppe) and is laid out like this
YeOldeShoppe
Shoppe
migrations
templates
index.html
urls.py
views.py
YeOldeShoppe
static
bread.jpg
settings.py
urls.py
manage.py
The code I'm having an issue with is in my index.html
{% load static %}
...
<div style="width: 25%; display: table-cell; text-align: center;">
<img src="{{STATIC_URL}}bread.jpg" alt="Great Value Bread"/>
<h2>Bread</h2>
<h5>$0.99</h5>
</div>
In my settings.py I've already set STATIC_URL
STATIC_URL = '/static/'
In my urls.py of Shoppe I tried to add it to urlpatterns
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
So far, I've tried to have the static folder be in the root directory of YeOldeShoppe
(eg. with manage.py), I've tried it in the YeOldeShoppe subdir (with settings.py) and in
my Shoppe subdir (with views.py). I tried having the both templates dir with the static dir
in the root (with manage.py), and I tried to use the command python manage.py collectstatic. I've also tried a variation of using "{{STATIC_URL}}bread.jpg" and "{% static "bread.jpg"%}".
index.html
{% load static %}
<img src="{% static "bread.jpg"%}" alt="Great Value Bread"/>
try adding these to the settings.py and urls.py:
settings.py
TEMPLATES = [
{
...
'DIRS': [...
(os.path.join(BASE_DIR, 'static')),
...
],
...
},
]
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Django v3.2 static files not serving in VS Code windows 11

I am trying to get static files to work in Django 3.2 (python 3.7) running in VS code (in Windows 11). My base template is referring to a style sheet at static/styles/style.css. The static folder is in the project root directory.
In my base template I have;
{% load static %}
<link rel="stylesheet" href="{% static 'styles/style.css'%}">
In my settings.py file, I tried both:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
And
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
I have also added the following to urls.py file:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
But I keep getting the following error:
"GET /static/styles/style.css HTTP/1.1" 404 179
Can someone please provide a solution?

why I can not in folder static inside app for project django

I can't get access to the STATIC folder for my Django project.
Here's my project structure.
-myproject
--core
--settings.py
--myapp
--static
--------myapp
---- js
---- css
--templates
--static
In settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR, "static"),
]
print STATICFILES_DIRS:
['/media/my_pc/Apps/my_project/static']
In my main urls.py, I use this:
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Now, when I try to call the static .js file, it doesn't work.
error blook:
this Error on call base.html foces to the blook javaScript
in base.html
..
{%block javascript%}
{%endblock javascript%}
in my_use_htm.html
{%block javaScript%}
{%endblock javaScript%}
foces the name blook

css and other static files not working in django

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!

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