I have developed my web application in Django Framework. I have also made the 404 and 500 Error pages and understand very much that, they can only work when DEBUG=False.
The problem now is that after setting DEBUG=False, my application which I have hosted on Heroku no longer shows. I am also using the whitenoise package for configuring my static files.
This are my settings.py as related to this issue
DEBUG = True
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfile'
STATICFILES_DIRS = [BASE_DIR / "static"]
MEDIA_URL = '/media/'
MEDIA_ROOT = "media"
NOTE: I have collected staticfiles using the command heroku run python manage.py collectstaic
I was able to solve the issue. When I removed the whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage', I noticed that i no longer got the error which read contact the administartor, and also my page was able to load and the 404 and 500 pages were loading correctly when i set the DEBUG=False
But I noticed that, the images where no longer showing. But I have a feeling that if I use aaws or cloudinary to host the images as well as server them, it should work perfectly.
Related
I am using Whitenoise to serve static files (images, css, js) for a Django site. Now my problem is that the static files seem to be "cached to much"(?) when working locally. Description of actions:
Initially my static files are served correctly
I edit a file in static/
I run ./manage.py collectstatic (which correctly identifies one updated file).
When going to http://127.0.0.1:8000/ my browser consistently shows the old stale version of the file. I have even tried completely removing the generated staticfiles/ folder - and the browser still seems to be able to dig out an old version of the file?
This is when running locally in debug mode. Do not have a consistent understanding of how it is in production, but I think it works better (as it should?) there.
My configuration:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
....
INSTALLED_APPS = [
# My apps
'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'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
("js" , BASE_DIR / "static/js"),
("css" , BASE_DIR / "static/css"),
("img" , BASE_DIR / "static/img")
]
I guess the problem is that I do not really understand the Whitenoise model - slightly frustrating as this should be quite simple??
Update: I have tested this in Firefox with Ctrl-Shift R to reload the page, and got the old version. But when actually deleting the browser cache explicitly things work. feels a bit excessive that I have to manually wipe the browser history - but I can live with that.
If a hard reload works, then the browser is most likely caching the parent request (rendered html result).
So if you have an endpoint, /myendpoint/, that returns a rendered template, where the template contains the static file reference handled by whitenoise , css/mycss.{hash}.css, the parent request is being cached and the browser doesn't see the updated static file reference.
Django has some tools that help dealing with browser-side caching.
https://docs.djangoproject.com/en/3.2/topics/cache/#controlling-cache-using-other-headers
If you want to make sure the client always get's the latest page you can use the never_cache decorator.
from django.views.decorators.cache import never_cache
#never_cache
def myview(request):
...
hi I have a problem when I upload a file to the deployed server. It returns 404 does not matter if I do it by admin or by a view but if I can see the files that are already on the server.
I am hosting my app in namecheap on a shareserver and the settings are
settings.py
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static-server')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media folder for database media
MEDIA_URL = '/static-server/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/static-server/media')
url.py
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True)
switch between debug mode true or false on local and it works perfectly but not when I deploy ... if anyone has any ideas. Well, from namecheap support they answered that the error is not on their side
Django does not serve media or static files in production as it just means to save the link for it. You need to use other services as Amazon Web Services S3 Bucket to serve it. But if you want to serve it anyway you can do in using Whitenoise.
First pip install whitenoise and then pip freeze > requirements.txt
Then in settings.py
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
then add this line
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
then push this code to your production server and make sure you run collectstatic command i.e python manage.py collectstatic your static files now should be working.
The static files always give me a 404 error and I can't see why,I copied a style I've used before but not with this version of django.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_DIR = [
os.path.join(BASE_DIR,"static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static'
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',
]
I was using cdn and style tag for the whole time working on the project but now i want to wrap it up and use some css/js files already ready for me.
I tried collecting the static files by python manage.py collectstatic and it collected all the static files in the static folder but still doesn't load them and returns a 404 error
my dir:
/Eyelizer
/App1
/App2
/Eyelizer
/static
/css
/main1.css
/Eyelizer
/css
/wanted.css
/js
/wanted.js
/images
/templates
/media
Every kind of help is appreciated and thank you.
I don't think there is anything like STATIC_DIR but it is STATICFILES_DIRS.
And also you have made a typo mistake in STATIC_ROOT while closing the bracket.
Just put the below in settings.py by removing all static related things.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
I am trying to deploy my webapp to heroku. I am using Django and the following is most of my settings.py file:
"""
Django settings for blog project on Heroku. For more info, see:
https://github.com/heroku/heroku-django-template
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import dj_database_url
import raven
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
try:
from .local_settings import *
except ImportError:
pass
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'blogapp',
'homeapp',
'nimfksapp',
'omniclipapp',
#Heroku Sentry
'raven.contrib.django.raven_compat',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
ROOT_URLCONF = 'blog.urls'
WSGI_APPLICATION = 'blog.wsgi.application'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "live-static", "media-root")
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
When running collectstatic locally the static files get collected fine and are served up on the web page. When I deploy the app to heroku (which automatically runs the collectstatic command for me) it throws up an "Internal Server Error (500)". I followed a recommendation on a similar SO page and added a sentry to the app through heroku and got a clearer error message:
ValueError/nimfks/ errorMissing staticfiles manifest entry for...
I tried changing (and removing) the STATICFILES_STORAGE without success. Removing it got me past the error but trying to display the actual static file (in this case an image) didnt work i.e. it wasnt loading.
I also tried changing the static settings to use PROJECT_ROOT instead of BASE_DIR and a lot of different configurations, all of which didnt work.
Am I missing something here? I cant seem to find an answer in the similar questions asked on SO.
EDIT
Answer:
Embarrasing as it is I want to keep this up since it might help someone else struggling with this. Issue in my case was that I was using .PNG in my html file instead of .png which was the real file extension. Didn't realize this was case sensitive. The real solution to this problem was essentially just having a sentry running that will catch these types of errors (see sentry docs). This is my final version of my static settings in the settings.py file:
import os
import dj_database_url
import raven
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
WSGI_APPLICATION = 'blog.wsgi.application'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Try to comment the line
'django.contrib.staticfiles',
inside INSTALLED_APPS
Firstly apologies for the length of this.
I have a django project running on Centos6 and Apache using a C-Panel plugin to install Django and I am trying to serve the static files in production.
My project uses Django 1.9 and I am trying to use Whitenoise to serve my static files.
My settings.py contains the following:
STATICFILES_STORAGE ='whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'common-static'),
And this is my MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
)
This is the wsgi.py for my django app
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
And this is the one generated by the plugin:
import os
import sys
import site
vepath = '/home/mysite/virtualenv3.5/lib/python3.5/site-packages'
prev_sys_path = list(sys.path)
site.addsitedir(vepath)
sys.path.append('/home/mysite/djangosites/mysite')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings"
application = get_wsgi_application()
I have DEBUG = False in my settings.py.
When I run ./manage.py collectstatic the files are collected and if I run the server with 0.0.0.0:8000 the static files are found.
I tried add the following to both wsgi.py files but to no avail:
from whitenoise.django importDjangoWhiteNoise
application = DjangoWhiteNoise(application)
Any advice on how to solve this would be appreciated.
It's a late response but it might help other people searching for an answer.
You do NOT have to include 'django.middleware.security.SecurityMiddleware' when you're using 'whitenoise.middleware.WhiteNoiseMiddleware'.
Also, you don't need to make any changes in wsgi.py. Adding the middleware will take care of everything for you.