I am able to deploy my app (via Django) to Heroku when DEBUG = True but when DEBUG = False I get a Server Error. I think it has to do with how I've set up my static files. When I comment out "STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'" I don't get an error message but the site is completely unformatted. Here's the relevant settings.py code:
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
...
]
ALLOWED_HOSTS = ['*']
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT= os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
I've added my static folder in all sorts of locations (same folder as settings.py, in the root folder, etc) to no avail.
Any ideas?
You may have forgotten to include the whitenoice middleware in your settings.py MIDDLEWARE setting. Edit your settings.py file and add WhiteNoise to the MIDDLEWARE_CLASSES list, above all other middleware apart from Django’s SecurityMiddleware:
MIDDLEWARE_CLASSES = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
#...
]
More information can be found in the whitenoise docs: http://whitenoise.evans.io/en/stable/django.html
Go through the step-by-step setup to see what you're missing. The Heroku docs tend to omit the middleware addition--which causes the bug--and perhaps there's something else missing for your application.
Those staticfile settings came directly from the Heroku website (https://devcenter.heroku.com/articles/django-assets). When I ran python manage.py collectstatic I got a key error 'DATABASE_URL' which I had to export a value for and then when I pushed my files to Heroku the website worked properly.
I've been facing the exact same problem but it's not the staticfiles its DEBUG = False that's causing the issue. When I realised it I remembered I visited a github repo yesterday that had the solution to my problem.
https://github.com/8sagh8/DjangoRestApi-part1-youtube-project/blob/main/README.md
You could keep changing DEBUG to False or True between production and development or you could use the code below
import sys
if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'):
DEBUG = True
else:
DEBUG = False
If you've worked with C programs this would look quite familiar, the code above checks if you typed in runserver at the end of python manage.py runserver and sets DEBUG to True but else it will set DEBUG to True
Related
As I state in the title, when I set DEBUG = False in my project's settings file, the files from my media directory (the one the user uploads) don't display. The files from my static directory (the CSS and JavaScript files) load properly.
I looked at this answer, but I don't understand the prerequisites to get this to work. I am testing this on my local machine, where I only have Django and PostgreSQL installed. I don't have any Apache servers running, as far as I'm aware. I want to deploy my app on Amazon AWS, so I'd like to try out how it will look in production there before I deploy it to Amazon AWS.
Here are the relevant parts of my settings.py file:
DEBUG = False
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]
Willem Van Onsem is right on the media files. Since the static file is OK, for the workaround, you can add this line to your urls.py in the folder containing settings.py:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have all the static files, but for some reason only the normal html loads with no css. I have tried using collectstatic and creating a new project but it doesn't work on any. STATIC_URL is also specified along with static in the url.py . Nothing seems to be working.
This can happen if your DEBUG is set to False and did not mention any staticfiles dir.
Okay, update your settings.py as below:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_my_proj"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
Now, that you have done that make dir called static_my_proj, at the same level where your manage.py file is.
Okay, now create new dir called static_cdn just one level up, i.e. one level up to manage.py file.
Now, create dir called static_root inside static_cdn and that is all you have to do. Make sure you run python manage.py collectstatic
NOTE:
static_my_proj is for development or DEBUG = True and static_cdn is for production or DEBUG = True. handy, right?
Also, you can add media file the same way, just add,
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
and make new dir called media_root under static_cdn.
Set DEBUG = True first and test it.
Hope this helps.
Im using Django 1.9 and Python 3.4.3.
When changing DEBUG = False on my app I'm getting a 500 error on all pages of my app.
Note: The Django admin page results in a 500 error as well. Some
other posts reported not getting this error on the admin page and I am. I have also tried everything in this post
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS =(
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
It will be better if you add the ADMINS to the settings:
ADMINS = (('Your name', 'Your#EMAIL'),)
With that you'll receive a better report when the error occur that you can use to debug the error.
Hope it helps
You may have forgotten to include the whitenoice middleware in your settings.py MIDDLEWARE setting. Edit your settings.py file and add WhiteNoise to the MIDDLEWARE_CLASSES list, above all other middleware apart from Django’s SecurityMiddleware:
MIDDLEWARE_CLASSES = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
#...
]
This is NOT necessary when DEBUG=True but when DEBUG=False, suddenly you have an issue. Heroku unfortunately don't include this middleware addition in their documentation and their demo apps run in DEBUG=True, so it's tough to find the issue.
More information can be found in the whitenoise docs: http://whitenoise.evans.io/en/stable/django.html
Go through the step-by-step setup to see what you're missing. The Heroku docs tend to omit the middleware addition--which causes the bug--and perhaps there's something else missing for your application.
Whitenoise is looking for something it can't find. I had a problem with this as well and never got it working. Depending on how many static files you have, decide if you really need to cache them.
If you don't, just leave it out.
If you do, you need to find what it is whitenoise is trying to find and give it that. Maybe this helps: https://stackoverflow.com/a/28385055/1322179
I've already tried the solution here and it didn't work for me. I'm creating a project based off the Heroku "Getting Started" project for Python.
In views.py, I'd like to be able to access a file in the static/data/ folder. However, most of my attempts I make to create the correct url to the file have failed. The only thing that works is putting the absolute path to the file as it exists on my local file system, which obviously won't work when I deploy my app.
Previous attempts to open the file include:
from django.templatetags.static import static
url = static('data/foobar.csv')
os.path.isfile(url) # False
from django.conf import settings
url = os.path.join(settings.STATIC_URL, 'data/foobar.csv')
os.path.isfile(url) # False
Here is my directory structure:
/appname
/app
/templates
views.py
/appname
/static
/js
/css
/data
settings.py
urls.py
settings.py:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
)
MIDDLEWARE_CLASSES = (
'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 = 'appname.urls'
WSGI_APPLICATION = 'appname.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Instead of joining the STATIC_ROOT with the filename, use the staticfiles_storage interface instead. This will also work with remote static files like S3/django-storages.
from django.contrib.staticfiles.storage import staticfiles_storage
url = staticfiles_storage.url('data/foobar.csv')
With staticfiles_storage you can also do simple file operations like open, delete, save.
The particular staticfiles storage backend you've configured will provide both a path method and a url method.
from django.contrib.staticfiles.storage import staticfiles_storage
p = staticfiles_storage.path('data/foobar.csv')
content = p.readlines()
# manipulate content
The .url method returns the same value as Django's static built-in
url = static('data/foobar.csv')
When you deploy a Django application to Heroku, or when you manually run manage.py collectstatic task, all the static assets will be copied to your STATIC_ROOT directory. Therefore you should use:
file_path = os.path.join(settings.STATIC_ROOT, 'data/foobar.csv')
STATIC_ROOT = 'staticfiles' is your problem. From the docs, STATIC_ROOT is:
The absolute path to the directory where collectstatic will collect static files for deployment.
Currently, you don't even have a path listed there...
Your static files are not at the same place when you are in "dev" or "prod".
In dev, you use the django "runserver" command which will serve your static file with "original" files (eg : myproject/src/appname/static/appname/images/plop.jpeg)
In production mode, you must use the "collectstatic" django command which will copy those original file in a "direct public http access folder" (eg : /static/appname/images/plop.jpeg for an http access)
But original files are still at the same place (myproject/src/appname/static/appname/images/plop.jpeg), so your view can access those original file directly.
If you know in which app the file your are looking for is, it is very simple. If you want to use the "static overwrite" mecanims of Django, have a look to its functions to get the "final" static file (for exemple, is it myproject/python-env/lib/python2.7/site-packages/coolapp/static/coolapp/images/plop.jpeg or myproject/src/myapp/static/coolapp/images/plop.jpeg)
I recommend to read the Django Doc about static finders to better understand how it works : https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_FINDERS
PS : "HTTP path" and "python path" are not the same ;)
Just had the same problem. Don't know if this is the best solution.
In settings.py I created two paths for switching between productive and development. I need to uncomment when deploying the site.
#Productive
#STATIC_ROOT = '/home/DimiDev/RESite/static'
#Development
STATIC_ROOT = 'realestate/static'
And in my python file, as already stated in this post.
from django.contrib.staticfiles.storage import staticfiles_storage
file_path = staticfiles_storage.path('realestate/ml/2xgBoosting_max.sav')
My structure for this file:
RESite\realestate\static\realestate\ml\2xgBoosting_max.sav
Let me tell you what I did, I made an app in which I had to read a CSV file.
I made the main project directory with django-startproject command and then made an app.
In the root I made a folder named static and inside that, I placed the CSV file.
Now in my views.py
read_csv('static/file_name')
All other settings were default and this worked for me!
What you are trying to do can be achieved the following way.
First as your settings.py file has this base path:
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
You can get files in your static directory this way:
url = os.path.join(settings.BASE_DIR, 'static/data/foobar.csv')
os.path.isfile(url) # True
So I installed Bitnami Django stack, and enabled the admin module, and followed the tutorial for creating an admin menu for "Polls".
However, when I go to /admin/ everything is white plaintext. All the css and images are 404 error.
All I did was:
enable in settings.py installed_apps:
'django.contrib.admin',
In urls.py UNcommented:
from django.contrib import admin
admin.autodiscover()
url(r'^admin/', include(admin.site.urls)),
uncommented.
In settings.py, I tried using default settings and also tried this:
MEDIA_ROOT = ''
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'static/'),
)
Nothing seems to work, it refuses to find static files in /admin/media/css/ etc.
I made sure my windows PATH has /bin of django. I even tried including /contrib, nothing helps.
I have installed Django to:
C:\DjangoStack\apps\django
I have installed my project to:
C:\Users\dexter\BitNami DjangoStack projects\Alpha
and I type: localhost/Alpha/admin to go to admin.
I almost missed the answer to this until I re-read your question and finally caught the bit in the last line: "and I type: localhost/Alpha/admin to go to admin". That means all your URL settings are wrong.
Currently, you have:
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
Whereas, these should be:
MEDIA_URL = '/Alpha/media/'
STATIC_URL = '/Alpha/static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
Additionally, you don't need "static/" in STATICFILES_DIRS. So remove that setting.
I'm from the BitNami Team and I just saw this issue. I'm not sure if you are using and older version but at least in the newer version of the BitNami DjangoStack you just need to make sure that the ADMIN_MEDIA_PREFIX point to /static/admin/ if you are following the
instructions in https://docs.djangoproject.com/en/1.3/intro/tutorial02/ . You don't need to copy the static files in your project directory because django automatically will use the files in django/contrib directory.
However currently we are setting the ADMIN_MEDIA_PREFIX to /static/admin/media because the behavior is different when the application is served by Apache instead of the django server. We realize that this may be a bit confusing for users that are just starting with django and we are looking at this on our side to keep the default configuration for the new projects but also allow the demo project to be served by Apache.