Problem: None of the changes I'm making to my CSS files are being applied to my HTML pages. And when I try and make new HTML/CSS files I get errors when I inspect the page in developer mode. The errors are saying they can't find my CSS files.
Exact error when I inspect my page in developer mode
GET http://127.0.0.1:8000/static/css/other.css net::ERR_ABORTED 404 (Not Found)
Background:
I'm creating a basic image editing site using django, html/css, and injecting JS to apply some filters to images. Previously I was able to make changes and they were reflected in the page, but now I can even delete my css file and it still uses an older version.
Things I've tried:
Gone into settings cleared browser cache
Disabled caching in developer mode
appended the version of css file ?v1.1 to force a rest (caused the 404 error from above)
Run collectstatic in terminal
Cleared cache opened site in private window
Watched several youtube vids on setting up static file dir and I think its correct. At some point in time my css was loading and updating as I made changes.
Directory Layout
These are my settings
Settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Image_API',
'rest_framework',
]
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 = 'Image_API.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',
],
},
},
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../static'),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), '../static')
Urls.py File
from django.contrib import admin
from django.urls import path
from Image_API import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('',views.upload2, name='upload'),
path('upload/', views.upload2, name='upload'),
path('other/', views.other),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root =settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
How my HMTL Files refrence css
I have load static at the top of the page and have my link to the css in the header tag.
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}">
It looks like the problem might be coming from your STATIC_URL setting and or STATIC_ROOT. Try changing it to:
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
You might also want to check that your urls.py file is setup correctly:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Restart your server after making these changes just to be sure.
ps: collect static is run during deployment
You might have overlooked and updated CSS in /staticfiles/css/
Instead try updating it in /media/css.
staticfiles directory is auto-generated when you run python manage.py collectstatic.
You can try deleting staticfiles directory and run python manage.py collectstatic and see if it fixes the issue.
Related
I've followed the Django 3 documentation to set my static file on my web .And i did load static in my template , but it still keeps tell me that the static tag is invalid . im super confused and dont know wheres the problem? Have anyone face this kind of problem ?
Error like this
TemplateSyntaxError at /
Invalid block tag on line 8: 'static'. Did you forget to register or load this tag?
Heres my directory structure
mblog/
|---maonsite/
|---mblog/
|---static/
|---css
|---js
|---images
|---templates
|---index.html
|---product.html
And heres the setting.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '^)azutlc_vkzxpw4ghw#b$+q6g)5&%lsamt)s0i*k*gdvw###b'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'maonsite',
]
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 = 'mblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS=[os.path.join(BASE_DIR, "static"),
'/var/www/static/',]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from . models import Post
# Create your views here.
def homepage(request): #index.html
return render(request,'index.html')
def productpage(request):
return render(request,'product.html')
and urls.py
from django.contrib import admin
from django.urls import path
from maonsite.views import homepage,productpage
urlpatterns = [
path('admin/', admin.site.urls),
path('',homepage),
path('product/',productpage),
]
Im appreciated for anyone who give me any piece of advice or solution
thx
Django: 3.0.7 Python: 3.8.3
In your main urls.py, have you added static URLs?
# urls.py
from . import settings
urlpatterns = [
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
For this to work, your settings.py file should have these variables defined
# settings.py
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Finally, in your templates, make sure you have this line
{% load static %}
I am currently working through some tutorials to enhance my knowledge of Django. In doing so, I decided to use to most recent version of Django. I have been able to overcome most of the divergences between my code and that of the tutorial except for one - static files are not being served. Now, I am not fully sure that the difference is strictly due to the Django version. Here is what is going on.
I have the following project structure:
settings.py
STATIC_URL = '/static/'
STATIC_FILES = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
What is interesting is that with this configuration, the project is able to find templates successfully. However, as mentioned above, it cannot find the static files. Why is that?
Also, this tutorial sets up an unusual configuration in that the static and templates directories are located inside the main app's directory, whereas I typically have them one level higher, i.e., in the project root's directory. Could this be a part of the problem? What in the settings of this particular project makes Django look for files one directory lower? The settings seem the same as those of other project I had done. However, those project contained the static and templates directories in the project's root directory.
Any help and clarification is appreciated.
Edit:
urls.py
from django.contrib import admin
from django.urls import path
from .views import home
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
try replacing this:
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
with
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Also provide the status of files (like 404 messages)
STATIC_FILES doesn't mean anything to Django, as far as I know, although maybe you are using it for another purpose.
The way you had STATIC_ROOT defined it was pointing to a non-existent directory.
There is a good reference in StackOverflow here
To serve static files you need to add the following configuration in urls.py as:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Next, I believe it is a good practice to put static and templates within their own apps, this is useful if you want to make that app plug-able any near future.
Or it is also a good practice to gather all static files in project level directory and add the following in settings to identify it.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
edit: I just see the updated question. Try adding this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This says, as long as we are in debug mode serve the static files.
try this:
STATIC_ROOT = os.path.join (BASE_DIR, "taskbuster", "static")
I was able to solve the issue by changing the settings to the following:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Furthermore, it was helpful to read the following documentation when trying to understand how to fix it
https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-STATICFILES_FINDERS
Particularly, this explained clearly what Django did:
The default will find files stored in the STATICFILES_DIRS setting
(using django.contrib.staticfiles.finders.FileSystemFinder) and in a
static subdirectory of each app (using
django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple
files with the same name are present, the first file that is found
will be used.
My project is named 'pages', and when I runserver I get this error. Anybody have any clue how to fix this error.
Page not found (404)
Request Method: GET Request URL: http://127.0.0.1:8000/ Using the
URLconf defined in pages_project.urls, Django tried these URL
patterns, in this order: admin/ The empty path didn't match any of
these. You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will display a
standard 404 page.
My settings.py file looks like this:
"""
Django settings for pages_project project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*u)%-zmf=2g-c*3z2-&=n=asty5v36n62^90_u*-#83!wb=)eq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages', # new
]
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 = 'pages_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'pages_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
And my urls.py in my 'pages' folder is
from django.urls import path
from . import views
urlpatterns = [
path(' ', views.HomePageView.as_view(), name='home'),
]
Any help would be greatly appreciated. Thanks.
The error is telling you that the main urls.py only includes the admin pattern. You also need to include the pages urls.
Also, you have a space in your path pattern. Remove it.
You have a space in your path; ' '. This would mean that the url is http://127.0.0.1:8000/%20. Delete the space.
path('', views.HomePageView.as_view(), name='home')
You project urls: Remove the space
pages/urls.py
urlpatterns = [
path(r'^$', views.HomePageView.as_view(), name='home'),
]
Add your app urls at your project urls so that way your project can see your app url
projectName/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
urlpatterns = [
...
url(r'^', include('pages.urls')),
]
I have CSS file at /ecomstore/static/css.css
I have already linked the css to the base.html within head tags by
<link rel="Stylesheet" type="text/css" href="/static/css.css" />
My urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from ecomstore import settings
from django.contrib.staticfiles import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^catalog/','preview.views.home'),
# url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
# { 'document_root' : '/home/yogesh/ecomstore/static' })
]
urlpatterns = [
# other commented code here
url(r'^catalog/?','preview.views.home'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root' : '/home/yogesh/ecomstore/static/' }),
]
Settings.py file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(CURRENT_PATH, 'templates')],
'DIRS': [os.path.join(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',
],
},
},
]
Static settings:
STATIC_URL = '/static/'
STATIC_ROOT = "/home/yogesh/ecomstore/static/"
Despite all this stuff i dont know why my css template is not loading. Also in the terminal i am getting the following indicating some sort of error.
[24/Nov/2015 11:11:36] "GET /static/css.css HTTP/1.1" 404 1735
Use {% static %} template tag:
{% load staticfiles %}
Configure static files dir in your settings and do not hardcode the path in your urlconf:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
)
Make sure you're serving static files during development:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Check that static file dir /home/yogesh/ecomstore/static/ is readable by your django process.
Static files
Store your files in /ecomstore/static/ecomstore/css.css instead of /ecomstore/static/css.css because Django look by default in all folders <app_name/static/<app_name>, then you don't have to had these folder in STATICFILES_DIRS variable.
Django documentation :
Store your static files in a folder called static in your app. For
example my_app/static/my_app/myimage.jpg.
Read this for more
information and configure your project : Managing static files
Templates
You did also a mistake in the configuration of your template. When you use os.path.json function, you don't have to have a / at the last folder. Just use os.path.join(BASE_DIR, 'templates')
Serving static file during development
Concerning serving static files, if you use the django built-in server, you don't have to configure anything, Django serve them by default. However, if you use gunicorn or uWSGI, yes you have to configure your project to serve static files.
You have to add this in your main <project_name>/<project_name>/urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now, your server will server static file based on STATIC_URL that you configured in your <project_name>/<project_name>/settings.py file.
Read this for more information : Serving static files during development
I'm newbie in django and I started learning django with official tutorial.
I use django beside virtualenv, but I have a problem with
the login page and admin page because
they aren't load css and show login
page and admin page without any style
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g8%o#ackd!hzekoho4rn7r7-t_m!sk$*nwi-4j556t=!ln3(#+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
First of all, Create folder named as "static", then you need to copy all the css/js file into static folder inside your project(or wherever you create static folder). Then declare the static files directory path in your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = ('assets', BASE_DIR +'/static/',)
In your html file, add following line - {% load staticfiles %} at top of the header section or top of the file.
In <head> section you can link the css/js file using following code
<link rel="stylesheet" href="{% static 'assets/css/mystyle.css'%}">
</link>
<script src="{% static 'assets/js/jquery.js'%}"></script>
You need to read through the documentation for serving static files. When you are in production, your webserver (nginx/apache) would be responsible for serving static files such as JS, CSS and images. So any request for an image or JS file would be taken care of immediately by the webserver while any request for an actual page would be passed to your application server (i.e. Django)
In development you need to tell the development server to actually serve your static files so you need to add the following to your root urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There are two situations that you maybe fail to load CSS files.
login Interceptor catch all the request, including your static files
browser cannot access your CSS files.
It is easy to judge what situation you are in. You can open your browser and check whether your CSS request is received. (for example, open your Chrome by F12 and check Console).
If there is not an error about failing to receive. Maybe your login Interceptor has caught all the things. And then, you can dig into what you received, at that you will find the answer. on my case, I find the response is my login page, not my ccs file.
You should let them go like this.
if static('') in request.path:
return self.get_response(request)
If received, you can see other answers.
(My English is not very good. If you want, you can edit this answer.)