Project name is exam. I place simple.css file in exam/static/css/. When I request http://127.0.0.1:8000/static/css/simple.css, it returns 404 error, saying 'css\simple.css' could not be found. The settings seem all right. In production environment the static requests are all right with nginx.
Related infomation:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\','/')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
],
'APP_DIRS': True,
},
]
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/')
STATIC_ROOT = os.path.join(BASE_DIR, "static").replace('\\','/')
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
)
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )
Perhaps you're missing the STATICFILES_DIRS setting.
When in production, python manage.py collectstatic moves all static files inside STATIC_ROOT directory so nginx can look up here for them, however in dev mode, django needs to know where the static files are, and use STATICFILES_DIRS tuple for that.
If you have these files inside exam/static, your STATICFILES_DIRS should looks like:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
If you are using ./manage runserver then you're missing STATICFILES_DIRS.
For nginx/gunicorn http://nginx.com/resources/admin-guide/serving-static-content/. Also Django White Noise
Related
I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally.
This is what I have done so far:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'content.apps.ContentConfig',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path.
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
import content.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', content.views.index, name='index'),
path('/about', content.views.about, name='about'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates:
{% load static %}
...
{% static "css/master.css" %}
resolves to
/static/css/master.css
[EDIT]
URL PATTERN looks like this
Using the URLconf defined in website.urls, Django tried these URL
patterns, in this order:
admin/
[name='index']
/about [name='about']
^static/(?P<path>.*)$
Opening a file directly ends up to a 404-django-page.
After that, I ran ./manage.py collectstatic successfully.
I am using the Django Dev server e.g. ./manage.py runserver...
I am maybe missing something, just need an additional pair of eyes. Thanks.
Solved it by removing
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and replacing it with
STATICFILES_DIRS = (os.path.join(BASE_DIR, "staticfiles"),)
I cant figure out how to make Azure App Service use css for admin panel.
In settings.py I included these:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
But somehow css is still not working for the admin panel.
How can I fix this? As far as I know Oryx which works under Azure App Service should automatically run
python manage.py collectstatic
Any ideas?
EDIT:
Installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'licenses_api',
]
There are something to check might help:
Click F12 on your Admin page to check if it is the 404 Not Found error.
Check the static files exist in your azure web app or not. You could see it in https://{your-web-app}.scm.azurewebsites.net/wwwroot/ site.
Check if your file structure match with the settings.py. Any spell error would make the static file not found.
If your file exists well, you should check if you use them correctly in your code like this answer. Here is how he use:
from django.conf.urls.static import static
urlpatterns = [
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Firstly try to add these code lines to
settings.py
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then import these lines to the
urls.py
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve
Finaly you have to add these lines to urlpatterns in
urls.py
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
(If you have not already created a static file please make sure to create one before you try this)
It's worked severl times for me and hope this will work for you too 😊
I'm trying to serve static files in my product review website, and I'm using Whitenoise, but It didn't work (can not find the files in /static) (when I test on local with DEFAULT = False, it still works)
I've tried to config wsgi file instead of using whitenoise middleware
This is my some code in my settings file to serve static.
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
Can you show me how to fix it? Pardon for my English
I tried to config the settings again:
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I don't have STATICFILES_DIRS, is it wrong?
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
But it still can not serve static files
I believe what you're missing is the STATICFILES_STORAGE. This is my settings.py related configuration.
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
ALLOWED_HOSTS = ["*"]
I followed the below configuration settings to resolve the issue.
DEBUG = False
ALLOWED_HOSTS = ['testnewapp.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'widget_tweaks',
'phonenumber_field',
'django_extensions',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Whitenoise Storage Class - Apply compression but don’t want the caching behaviour
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
# Comment the below line
# django_heroku.settings(locals())
Things to Remember
Make sure you’re using the static template tag to refer to your static files, rather that writing the URL directly. For example:
{% load static %}
<img src="{% static "images/error.jpg" %}" alt="OOps!" />
<!-- DON'T WRITE THIS -->
<img src="/static/images/error.jpg" alt="OOps!" />
If you get an error message with collectstatic, simply disable it by instructing Heroku to ignore running the manage.py collecstatic command during the deployment process.
But if you need to use WhiteNoise with any WSGI application
You need to wrap your existing WSGI application in a WhiteNoise instance and tell it where to find your static files. For example:
from my_project import MyWSGIApp
application = MyWSGIApp()
application = WhiteNoise(application, root='/path/to/static/files')
application.add_files('/path/to/more/static/files', prefix='more-files/')
Note
These instructions apply to any WSGI application. However, for Django applications you would be better off using the WhiteNoiseMiddleware class which makes integration easier.
#
http://whitenoise.evans.io/en/stable/base.html
I have been trying to create a django application, but there is a problem with django rendering static files:
Here is my setting files static configuration:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
I have placed all the static files in a static folder inside the location where manage.py resides.
Here you defined an STATIC_ROOT, so you after placing your static files and on each change of your css or js files you need to run
python manage.py collectstatic
This command will gather all static files into the defined dictionary, but this is done after the completion of development. So instead of that you can use STATICFILES_DIRS during development,
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
which will automatically find the static files during your development period.
Also make sure you have staticfiles in installed apps.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', # it's is used for static files
]
In your template you can load static files like
{% load staticfiles %} # register static tag
<link ref="stylesheet" href="{% static 'style.css' %}">
settings.py
INSTALLED_APPS = [
...
...
'django.contrib.staticfiles',
...
...
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
urls.py (main project's urls.py)
from django.conf.urls.static import static
urlpatterns = [
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I am unable to use CSS and JS files in my django project.
Folder structure:
mysite/
mysite/mysite/settings.py
mysite/mysite/templates/base.html
mysite/mysite/assets/css/...
settings.py
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = 'static'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',...)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
base.html
running python manage.py collectstatic returns:
"Your STATICFILES_DIRS setting is not a tuple or list; "
django.core.exceptions.ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
You never manually put anything STATIC_ROOT. It is only a dumping ground for collectstatic in production; it shouldn't even exist in development.
All of your static resources need to go in one of your apps' static directories, or if you need project-wide resources, you must create an entirely different directory for that is not the same as either MEDIA_ROOT or STATIC_ROOT and add it to STATICFILES_DIRS:
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'assets'),
)
You can call it whatever you want; I typically use "assets". Just don't name it "static", "media", "site_media", etc., just to avoid confusion.