I'm working with django, and trying to deploy my app to heroku.
All is working without any problems in local (even with DEBUG=False), but when deployed to heroku, the admin template doesn't display when DEBUG=False.
I followed theses instructions to configure my settings.py : https://devcenter.heroku.com/articles/django-assets
And here is my Procfile :
web: gunicorn bourse_logements.wsgi -b 0.0.0.0:$PORT
Feel free to ask if yu need some parts of my settings.py, I will paste them
Any help would be appreciated
EDIT :
Here is my settings.py :
https://gist.github.com/e-goz/62f812ab1fa8f8268f94
Are you sure you didn't .gitignore the templates folder?
* Add This line to your setting.py*
ADMIN_MEDIA_PREFIX = '/static/admin/'
you have to also copy all admin CSS and JavaScript to your static path(within static folder)
like static/admin/"you staticfiles"
You can try This setting as per your configuration on setting.py.
from unipath import Path
PROJECT_DIR = Path(__file__).ancestor(3)
PROJECT_ROOT = Path(__file__).ancestor(2)
sys.path.insert(0, Path(PROJECT_ROOT, 'apps'))
MEDIA_ROOT = PROJECT_DIR.child("media")
MEDIA_URL = '/media/'
STATIC_ROOT = PROJECT_DIR.child("collected_static")
STATIC_URL = '/static/'
STATICFILES_DIRS = (
PROJECT_DIR.child("static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
TEMPLATE_DIRS = (
Path(PROJECT_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
)
# Heroku specific settings
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# You can also try in your url.py
if settings.LOCAL_DEV:
baseurlregex = r'^media/(?P<path>.*)$'
urlpatterns += patterns('',
(baseurlregex, 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Related
I was trying to deploy my Django project on Render . Everything works fine except for the media files. I can't figure out the issue here.
I have added the followings into my settings.py:
DEBUG=False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
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',
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = '/contents/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/contents/')
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
urls.py
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)
I have created a Post (using models) before deploying. It had an image located a ./static/contents/Screenshot_334.png After deploying this image is accessible at https://someusername.onrender.com/static/contents/Screenshot_334.png . But if I create a new post from the deployed site I get a 404 error. The site doesn't cause any issue while its in the development mode.
Here's a portion of LOGS from Render:
https://someusername.onrender.com/static/contents/Screenshot_334.png (created while development) is accessible but https://someusername.onrender.com/static/contents/Screenshot_1.png (created post-production) is inaccessible. Also, static files (css, js) working fine.
I checked all the files and directories using the following piece of code:
res = []
for path, subdirs, files in os.walk('./'):
for name in files:
res.append(os.path.join(path, name))
Screenshot_334.png and Screenshot_1.png both are in the same directory
I also tried switching MEDIA_URL and MEDIA_ROOT to 'contents', 'contents/', 'static/contents/' and all the possible variations.
UPDATE:
I have found a workaround since I couldn't figure it out myself. I have mapped media to the urls.py and used FileResponse
Here's how views.py looks:
from django.http import FileResponse
def media(request, path:None):
img = open('./contents/'+path, 'rb')
response = FileResponse(img)
return response
I'm aware this might cause security issues but I think it won't do me any harm since it is a project just for learning.
Add whitenoise in your installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'whitenoise',
'accounts',
]
then add whitenoise.middleware.WhiteNoiseMiddleware in your middleware right after the first line.
try configring the static files as below in your settings.py
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = 'contents/'
MEDIA_ROOT = BASE_DIR / 'static/contents'
edit your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path(....)
]
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
I´m trying to install bower on a django project I have.
I executed both:
npm install -g bower
and
pip install django-bower
if I writebower --version
I get:1.4
however on my django project when writing
py manage.py bower install
or
py manage.py bower_install
I get Unknown Command: 'bower'
This is my setting.py
"""
Django settings for agenda project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
PROJECT_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), ".."),
)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
TEMPLATE_PATH,
)
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#7j23xm3jv=(#gicejabv2ppa$063st+d#)2x^thld0(#!chwq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
'modulo_agenda',
'schedule',
'djangobower',
)
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.locale.LocaleMiddleware',
)
ROOT_URLCONF = 'agenda.urls'
WSGI_APPLICATION = 'agenda.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/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.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_DIR, "site_media")
ADMIN_MEDIA_PREFIX = '/media/'
MEDIA_URL = '/site_media/'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
BOWER_COMPONENTS_ROOT = os.path.join(PROJECT_ROOT, "components")
BOWER_INSTALLED_APPS = (
'jquery',
'bootstrap'
)
FIRST_DAY_OF_WEEK = 1 # Monday
Can anyone tell me what I´m doing wrong?
bower is installed on my computer but somehow I cannot get the manage.py script to recrognize it as a valid command. Maybe I forgot something on the manage.py?
Thanks for the help.
As referenced here: https://github.com/nvbn/django-bower/issues/34
./manage.py bower_install
Hope this works.
Right now
If I added these setting to settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'project',
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
It will search for index.html in
where_manage_py_is_at/project/templates/index.html
not
where_manage_py_is_at/templates/index.html
which is very perplexing since
os.path.join(BASE_DIR, 'templates'),
refers to
where_manage_py_is_at/templates/index.html
Can someone tell me why is django doing this?
Thanks
If you want to do like this,try
in manage.py #at top of file like
#!/usr/bin/env python
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
in settings.py
from manage import BASE_DIR as T_BASE_DIR
TEMPLATE_DIRS = (
os.path.join(T_BASE_DIR, 'templates'),
)
This is my settings.py looks like :
kProjectRoot = abspath(normpath(join(dirname(__file__), '..')))
MEDIA_ROOT = os.path.join(kProjectRoot, 'abc/media/')
MEDIA_URL = '/media/'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'south',
'xlrd',
'pipeline',
)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_YUI_BINARY='C:/Python27/Lib/site-packages/yuicompressor-2.4.8-py2.7.egg/yuicompressor'
PIPELINE_JS = {
'site': {
'source_filenames': (
'media/js/zk.base.js',
'media/js/zk.popupmenu.js',
'media/js/zk.tree.js',
'media/js/zk.treenode.js',
),
'output_filename': 'media/js/script.min.js',
}
}
What is the mistake i am doing , please guide me . I think that it should create a script.min.js in my media/js/ , which i can load in templates.
Did you run ./manage.py collectstatic --noinput
If that doesn't work, make sure these are in your settings.py and run collectstatic again, your assets will be under the build folder.
PIPELINE_ENABLED = True
STATICFILES_FINDERS = (
'pipeline.finders.FileSystemFinder',
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
'pipeline.finders.CachedFileFinder',
)
STATIC_ROOT = normpath(join(SITE_ROOT, 'build'))
STATIC_URL = '/assets/'
STATICFILES_DIRS
STATICFILES_DIRS = (
normpath(join(SITE_ROOT, 'static')),
)
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
)
Then you can use your assets by putting the following in your template:
{% load compressed %}
{% compressed_js 'site' %}
Hope it helps.
Replace back-slashes \ with forward-slashes / in the path of PIPELINE_YUI_BINARY.
this is my first django app and I Have received the following msg:
Page not found (404)
Request Method: GET
Request URL:
Using the URLconf defined in _3Ms.urls, Django tried these URL patterns, in this order:
^ ^$ [name='vista_principal']
^admin/doc/
^admin/
The current URL, home/, didn't match any of these.
my setting.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '7th)hsx0w5mwlv+oty62w(us7&xtiw#y0&12)67ld%6y1-a)4f'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = '_3Ms.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = '_3Ms.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'apps',
)
_3Ms/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', '_3Ms.views.home', name='home'),
# url(r'^_3Ms/', include('_3Ms.foo.urls')),
url(r'^', include('apps.es.urls')), # incluye las urls de es.urls.py
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
es/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('apps.es.view',
url(r'^$', 'home_view', name='vista_principal'),
)
es/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def home_view(request):
return render_to_response('es/home.html', context_instance=RequestContext(request))
You don't have a url for home/.
If you added url(r'^home/$', 'home_view', name='vista_principal'), it would have something to go to.