Collectstatic error while deploying Django app to Heroku - python
I'm trying to deploy a Django app to Heroku, it starts to build, download and installs everything, but that's what I get when it comes to collecting static files
$ python manage.py collectstatic --noinput
remote: Traceback (most recent call last):
remote: File "manage.py", line 10, in <module>
remote: execute_from_command_line(sys.argv)
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
remote: utility.execute()
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
remote: self.fetch_command(subcommand).run_from_argv(self.argv)
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
remote: self.execute(*args, **cmd_options)
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
remote: output = self.handle(*args, **options)
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 168, in handle
remote: collected = self.collect()
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect
remote: for path, storage in finder.list(self.ignore_patterns):
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
remote: for path in utils.get_files(storage, ignore_patterns):
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
remote: directories, files = storage.listdir(location)
remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 300, in listdir
remote: for entry in os.listdir(path):
remote: OSError: [Errno 2] No such file or directory: '/app/blogproject/static'
remote:
remote: ! Error while running '$ python manage.py collectstatic --noinput'.
remote: See traceback above for details.
remote:
remote: You may need to update application code to resolve this error.
remote: Or, you can disable collectstatic for this application:
remote:
remote: $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote: https://devcenter.heroku.com/articles/django-assets
remote:
remote: ! Push rejected, failed to compile Python app
remote:
remote: Verifying deploy...
remote:
remote: ! Push rejected to pin-a-voyage.
This is the whole settings.py file
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = 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 = '*********************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'custom_user',
'django_markdown',
'parsley',
)
#### AUTH ###
AUTH_USER_MODEL = 'custom_user.CustomUser'
AUTHENTICATION_BACKENDS = (
'custom_user.backends.CustomUserAuth',
'django.contrib.auth.backends.ModelBackend',
# 'django.contrib.auth.backends.RemoteUserBackend',
)
#############
#### EMAIL ###
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = '***' #my gmail password
EMAIL_HOST_USER = 'voyage.pin#gmail.com' #my gmail username
DEFAULT_FROM_EMAIL = 'voyage.pin#gmail.com'
SERVER_EMAIL = 'voyage.pin#gmail.com'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
##############
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 = 'blogproject.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 = 'blogproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'blogproject',
'USER': '***',
'PASSWORD': '***',
'HOST': 'localhost',
'PORT': '',
}
}
# 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
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# 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 = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
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.django.GzipManifestStaticFilesStorage'
This is the structure of the project
blog-project -- blog -- migrations
-- static
-- templates
-- blogproject
-- blogprojectenv
-- custom_user
-- media
-- .git
Any thoughts?
I just updated to Django 1.10 today and had the exact same problem.
Your static settings are identical to mine as well.
This worked for me, run the following commands:
disable the collectstatic during a deploy
heroku config:set DISABLE_COLLECTSTATIC=1
deploy
git push heroku master
run migrations (django 1.10 added at least one)
heroku run python manage.py migrate
run collectstatic using bower
heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput'
enable collecstatic for future deploys
heroku config:unset DISABLE_COLLECTSTATIC
try it on your own (optional)
heroku run python manage.py collectstatic
future deploys should work as normal from now on
You have STATICFILES_DIRS configured to expect a static directory in the same directory as your settings.py file, so make sure it's there not somewhere else.
Also, do you have any files in that static directory? If you don't then git won't track it and so although it exists locally it won't exist in git. The usual solution to this is to create an empty file called .keep in the directory which will ensure that git tracks it. But once you have some static files in this directory then it won't be a problem anymore.
DO NOT disable collectstatic on heroku with heroku config:set DISABLE_COLLECTSTATIC=1. This will just hide the error and not make your app healthy.
Instead, it's better to understand why the collectstatic command fails because it means something is not right with your settings.
Step 1
Run locally both commands:
python manage.py collectstatic
python manage.py test
You should see one or more error messages. Most of the time, it's a missing variable (for ex: STATIC_ROOT) you must add to your project settings.py file.
It's necessary to add the test command because some collectstatic related issues will only surface with test, such as this one
Step 2
Once you've fixed all the error messages locally, push again to heroku.
Troubleshooting
Remember you can also run commands directly in your heroku VM.
If you cannot reproduce locally, run the collecstatic command in heroku and check what's going on directly in your production environment:
python manage.py collectstatic --dry-run --noinput
(Same goes for heroku console obviously)
Run python manage.py collectstatic locally and fix any errors. In my case there were reference errors that prevented that command from running successfully.
if you use django-heroku library
maybe you forget for put this setting in the bottom of line text settings.py for can possible read all config parameters
import django_heroku
django_heroku.settings(locals())
as like as the documentation:
Usage of Django-Heroku
In settings.py, at the very bottom::
…
# Configure Django App for Heroku.
import django_heroku
django_heroku.settings(locals())
This will automatically configure DATABASE_URL, ALLOWED_HOSTS, WhiteNoise (for static assets), Logging, and Heroku CI for your application.
p.s: sorry for my bad english
This error has occurred because you do not have staticfiles in
your Project's Root Directory.
Don't worry. The solution is SIMPLE.
You only need TWO STEPS.
Step 1: Open your settings.py file and write
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_ROOT = BASE_DIR / 'staticfiles'
Step 2: Run below given command in terminal in your Project's root directory.
(If you are using any Virtual environment for Django Project then go inside your Virtual environment and then go into your Project's root directory and then run below given command.)
python manage.py collectstatic
Congrats : Your Problem is Solved.
Now, you can COMMIT and PUSH your "changes" so that it is reflected in your Repository and then you are good to go.
This worked for me:
step 1 - heroku config:set DISABLE_COLLECTSTATIC=1
step 2 - git push heroku master
I face same problem..
Follow this step
heroku config:set DISABLE_COLLECTSTATIC=1
git push heroku master
python manage.py collectstatic
python manage.py test
If any error occurred after running test..check your
STATIC_ROOT is correct like this ==> STATIC_ROOT = os.path.join(BASE_DIR, 'static').
After run collectstatic command check all static files are
store in static directory for your root dir. level(manage.py
dir. level)...
heroku run python manage.py collectstatic.
heroku run python manage.py migrate
heroku config:unset DISABLE_COLLECTSTATIC (for future use).
Heroku had made a document with suggestions on how to handle this https://devcenter.heroku.com/articles/django-assets
add to settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
make a directory in the root of your project called staticfiles, put a favicon or something in there, just make sure git tracks it. Then the collectstatic command should finish on heroku.
Ran to that issue after trying to deploy an app again. The problem got cured after I specified these commands:
$ heroku config:set SECRET_KEY="*secret_key*"
$ heroku config:set DEBUG_VALUE="True"
$ heroku config:set EMAIL_USER="*user-email*"
$ heroku config:set EMAIL_PASS="*pass*"
These variables in settings.py were invoked with local environment variables,
which heroku didn't have on its environment, hence the error.
It seems to me that it's having problems creating that blogproject/static folder. I see you have a static folder inside your blog app, but it should be up one level in your blogproject folder.
Try creating a static folder inside your blogproject folder and that error should go away.
Today, not all of the requirements came in properly with $ pipenv install django from the heroku-django-template and $ pip install -r requirements.txt.
The latest version of the template includes a /static folder with a humans.txt, so the previous solution is likely not the proplem
Try running $ pipenv install whitenoise and then $ pip freeze > requirements.txt.
If that works, I would recommend $ pip install psycopg2 --ignore-installed and $ pip freeze > requirements.txt as well, otherwise you will similarly have problems migrating.
I faced the same issue while deploying my app. I realized I had updated my pip version, installed few plugins but forgot to create a fresh requirements.txt file.
Run pip freeze > requirements.txt in your terminal
Run python manage.py collectstatic
Now push the code to github and deploy to heroku server
Hope this helps if that is the case
insert this line of code to your setting.py file.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
In my case was an error almost like described above, after push-ing that resulted in errors, I set the SECRET_KEY "heroku config:set SECRET_KEY='*************************'",
git push heroku main (again)
,
heroku run python manage.py migrate
,
heroku run python manage.py createsuperuser .. and everything
,
heroku open
and it worked :)
removing STATICFILES_DIRS worked in my case
heroku config:set DISABLE_COLLECTSTATIC=1 --app #yourappname
Just run the command
This problem occurs because Heroku tries to run manage.py.
While executing manage.py
we have to write like
python manage.py 'some_command'
But Heroku tries it as
python manage.py --noinput
So in this case we can make changes to our manage.py file:
Initialy it looks like this:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'your_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv) # just put this in try block
if __name__ == '__main__':
main()
So we change our main.py to:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'your_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
try:
execute_from_command_line(sys.argv) # just put this in try block
except:
pass
if __name__ == '__main__':
main()
If you used .env files and python-decouple you'll have to define the environmental variables in Heroku app settings > Config Vars. Otherwise collectstatic won't work.
After testing everything that was posted on this thread, here's what worked for me:
Keep the Heroku environment variable DISABLE_COLLECTSTATIC set to 0, as it won't really solve the issue, but just mask it and mess with your site's assets
When using django_heroku lib on the settings file, include the argument "staticfiles=False", like this: django_heroku.settings(locals(), staticfiles=False)
The STATIC_ROOT variable on settings.py should be set as STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles'), being BASE_DIR set as BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))). This is described on Heroku's django-assets doc
After doing all that, run a python manage.py migrateon Heroku CLI and you should see a message about assets downloaded.
Before making it to actually work, the collectstatic command python manage.py collectstatic on Heroku CLI was giving a correct output, so be aware that you may get no errors with this command, but still have something wrong going on.
Related
Django admin template css is not loaded when deploy it in Heroku?
this is the admin page deployed in heroku, enter image description here here is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' deploy_settings.init.py DEBUG = False STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] I tried to run python manage.py collectstatic locally, and run it in heroku bash also, but it didn't work. Do we actually need to run this command? or staticfiles are collected when pushing to heroku master? I tried to add DEBUG_COLLECTSTATIC=1 in heroku config variables, but it doesn't work. one last note, I tried to install whitenoise and add it to the settings.py middlewars, and add STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' in deply_settings.init.py but I recieved this error, enter image description here when
It is been fixed by removing this line in deploy_settings.init.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Gunicorn with Django giving a problem with static files
Got a Django project named django_server. When I run python manage.py runserver the page shows up as expected Then, if I run gunicorn django_server.wsgi:application --bind 0.0.0.0:8000 The page shows without styling Checking the console, can see the following errors for both .css and .js files The resource from “http://0.0.0.0:8000/static/....css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). In the terminal where the gunicorn command was executed, can read NOT FOUND: /static/rest_framework/css/bootstrap.min.css NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css ... In settings.py I mention BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') This is the folder structure Checked the permissions in static folder (ls -l)and they show as drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static Checking the permissions in the files where the problem happens and Added also to settings.py import mimetypes mimetypes.add_type("text/css",".css",True) mimetypes.add_type("text/javascript",".js",True) But the error remains.
You need to run python manage.py collectstatic. On your settings.py I recommend you to use whitenoise to serve your files. 1) pip install whitenoise 2) Add STATICFILES_STORAGE on settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' 3) Add to your MIDDLEWARE on settings.py `MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', ... ]
Support needed for Django app deployment on Heroku
I have an app I'd like to deploy on Heroku. Not finished yet but it's now a requirement from my teacher. I created an account and app on heroku and use the GitHub deployment method but when I click on deploy branch I have the following type of error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_0f3c3e792cd2015b5d316aad8cf28d6c/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, Can you help me understand the error and solve it? I'd like to use this deployment method if possible as I am very much a begginer in git too and I'd like to avoid doing it with CLI for now. Thanks, Edit: As required Requirements.txt pasted: asgiref==3.2.3 Brotli==1.0.7 certifi==2020.4.5.1 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.3 django-crispy-forms==1.9.0 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 psycopg2==2.8.5 pytz==2019.3 requests==2.23.0 six==1.14.0 sqlparse==0.3.0 urllib3==1.25.9 whitenoise==5.0.1
I don't know what is the state of your settings but make sure your static urls are all created in settings.py. Specially the STATICFILES_DIRS which will set a place to collect the statics for production. Please follow this Heroku KB: https://devcenter.heroku.com/articles/django-assets | # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Then it should collect static in the right folder. Let me know.
Please use whitenoise to deploy static files on heroku.
Deploying a local django app using openshift
I've built a webapp using django. In order to host it I'm trying to use openshift but am having difficulty in getting anything working. There seems to be a lack of step by steps for this. So far I have git working fine, the app works on the local dev environment and I've successfully created an app on openshift. Following the URL on openshift once created I just get the standard page of "Welcome to your Openshift App". I've followed this https://developers.openshift.com/en/python-getting-started.html#step1 to try changing the wsgi.py file. Changed it to hello world, pushed it and yet I still get the openshift default page. Is there a good comprehensive resource anywhere for getting local Django apps up and running on Openshift? Most of what I can find on google are just example apps which aren't that useful as I already have mine built.
Edit: Remember this is a platform-dependent answer and since the OpenShift platform serving Django may change, this answer could become invalid. As of Apr 1 2016, this answer remains valid at its whole extent. Many times this happened to me and, since I had to mount at least 5 applications, I had to create my own lifecycle: Don't use the Django cartridge, but the python 2.7 cartridge. Using the Django cart. and trying to update the django version brings many headaches, not included if you do it from scratch. Clone your repository via git. You will get yourproject and... # git clone yourrepo#rhcloud.com:app.git yourproject <- replace it with your actual openshift repo address yourproject/ +---wsgi.py +---setup.py *---.openshift/ (with its contents - I omit them now) Make a virtualenv for your brand-new repository cloned into your local machine. Activate it and install Django via pip and all the dependencies you would need (e.g. a new Pillow package, MySQL database package, ...). Create a django project there. Say, yourdjproject. Edit Create, alongside, a wsgi/static directory with an empty, dummy, file (e.g. .gitkeep - the name is just convention: you can use any name you want). #assuming you have virtualenv-wrapper installed and set-up mkvirtualenv myenvironment workon myenvironment pip install Django[==x.y[.z]] #select your version; optional. #creating the project inside the git repository cd path/to/yourproject/ django-admin.py startproject yourjdproject . #creating dummy wsgi/static directory for collectstatic mkdir -p wsgi/static touch wsgi/static/.gitkeep Create a django app there. Say, yourapp. Include it in your project. You will have something like this (django 1.7): yourproject/ +---wsgi/ | +---static/ | +---.gitkeep +---wsgi.py +---setup.py +---.openshift/ (with its contents - I omit them now) +---yourdjproject/ | +----__init__.py | +----urls.py | +----settings.py | +----wsgi.py +---+yourapp/ +----__init__.py +----models.py +----views.py +----tests.py +----migrations +---__init__.py Set up your django application as you'd always do (I will not detail it here). Remember to include all the dependencies you installed, in the setup.py file accordingly (This answer is not the place to describe WHY, but the setup.py is the package installer and openshift uses it to reinstall your app on each deploy, so keep it up to date with the dependencies). Create your migrations for your models. Edit the openshift-given WSGI script as follows. You will be including the django WSGI application AFTER including the virtualenv (openshift creates one for python cartridges), so the pythonpath will be properly set up. #!/usr/bin/python import os virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: execfile(virtualenv, dict(__file__=virtualenv)) except IOError: pass from yourdjproject.wsgi import application Edit the hooks in .openshift/action_hooks to automatically perform db sincronization and media management: build hook #!/bin/bash #this is .openshift/action/hooks/build #remember to make it +x so openshift can run it. if [ ! -d ${OPENSHIFT_DATA_DIR}media ]; then mkdir -p ${OPENSHIFT_DATA_DIR}media fi ln -snf ${OPENSHIFT_DATA_DIR}media $OPENSHIFT_REPO_DIR/wsgi/static/media ######################### end of file deploy hook #!/bin/bash #this one is the deploy hook .openshift/action_hooks/deploy source $OPENSHIFT_HOMEDIR/python/virtenv/bin/activate cd $OPENSHIFT_REPO_DIR echo "Executing 'python manage.py migrate'" python manage.py migrate echo "Executing 'python manage.py collectstatic --noinput'" python manage.py collectstatic --noinput ########################### end of file Now you have the wsgi ready, pointing to the django wsgi by import, and you have your scripts running. It is time to consider the locations for static and media files we used in such scripts. Edit your Django settings to tell where did you want such files: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'static'),) TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'templates'),) Create a sample view, a sample model, a sample migration, and PUSH everything. Edit Remember to put the right settings to consider both environments so you can test and run in a local environment AND in openshift (usually, this would involve having a local_settings.py, optionally imported if the file exists, but I will omit that part and put everything in the same file). Please read this file conciously since things like yourlocaldbname are values you MUST set accordingly: """ Django settings for yourdjproject 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 BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ON_OPENSHIFT = False if 'OPENSHIFT_REPO_DIR' in os.environ: ON_OPENSHIFT = True # 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 = '60e32dn-za#y=x!551tditnset(o9b#2bkh1)b$hn&0$ec5-j7' # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'yourapp', #more apps here ) 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', ) ROOT_URLCONF = 'yourdjproject.urls' WSGI_APPLICATION = 'yourdjproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases if ON_OPENSHIFT: DEBUG = True TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'youropenshiftgenerateddatabasename', 'USER': os.getenv('OPENSHIFT_MYSQL_DB_USERNAME'), 'PASSWORD': os.getenv('OPENSHIFT_MYSQL_DB_PASSWORD'), 'HOST': os.getenv('OPENSHIFT_MYSQL_DB_HOST'), 'PORT': os.getenv('OPENSHIFT_MYSQL_DB_PORT'), } } else: DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #If you want to use MySQL 'NAME': 'yourlocaldbname', 'USER': 'yourlocalusername', 'PASSWORD': 'yourlocaluserpassword', 'HOST': 'yourlocaldbhost', 'PORT': '3306', #this will be the case for MySQL } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'yr-LC' TIME_ZONE = 'Your/Timezone/Here' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'static'),) TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'templates'),) Git add, commit, push, enjoy. cd path/to/yourproject/ git add . git commit -m "Your Message" git push origin master # THIS COMMAND WILL TAKE LONG # git enjoy Your sample Django app is almost ready to go! But if your application has external dependencies it will blow with no apparent reason. This is the reason I told you to develop a simple application. Now it is time to make your dependencies work. [untested!] You can edit the deploy hook and add a command after the command cd $OPENSHIFT_REPO_DIR, like this: pip install -r requirements.txt, assuming the requirements.txt file exists in your project. pip should exist in your virtualenv, but if it does not, you can see the next solution. Alternatively, the setup.py is an already-provided approach on OpenShift. What I did many times is -assuming the requirements.txt file exists- is: Open that file, read all its lines. For each line, if it has a #, remove the # and everything after. strip leading and trailing whitespaces. Discard empty lines, and have the result (i.e. remaining lines) as an array. That result must be assigned to the install_requires= keyword argument in the setup call in the setup.py file. I'm sorry I did not include this in the tutorial before! But you need to actually install Django in the server. Perhaps an obvious suggestion, and every Python developer could know that beforehand. But seizing this opportunity I remark: Include the appropriate Django dependency in the requirements.txt (or setup.py depending on whetheryou use or not a requirements.txt file), as you include any other dependency. This should help you to mount a Django application, and took me a lot of time to standarize the process. Enjoy it and don't hesitate on contacting me via comment if something goes wrong Edit (for those with the same problem who don't expect to find the answer in this post's comments): Remember that if you edit the build or deploy hook files under Windows and you push the files, they will fly to the server with 0644 permissions, since Windows does not support this permission scheme Unix has, and has no way to assign permissions since these files do not have any extension. You will notice this because your scripts will not be executed when deploying. So try to deploy those files only from Unix-based systems. Edit 2: You can use git hooks (e.g. pre_commit) to set permissions for certain files, like pipeline scripts (build, deploy, ...). See the comments by #StijndeWitt and #OliverBurdekin in this answer, and also this question for more details.
1) Step 1 install Rubygems Ubuntu - https://rubygems.org/pages/download Windows - https://forwardhq.com/support/installing-ruby-windows $ gem or C:\Windows\System32>gem RubyGems is a sophisticated package manager for Ruby. This is a basic help message containing pointers to more information…….. 2) Step 2: $ gem install rhc Or C:\Windows\System32> gem install rhc 3) $ rhc Or C:\Windows\System32> rhc Usage: rhc [--help] [--version] [--debug] <command> [<args>] Command line interface for OpenShift. 4) $ rhc app create -a mysite -t python-2.7 Or C:\Windows\System32> rhc app create -a mysite -t python-2.7 # Here mysite would be the sitename of your choice #It will ask you to enter your openshift account id and password Login to openshift.redhat.com: Enter your openshift id here Password : ********** Application Options --------------------- Domain: mytutorials Cartridges: python-2.7 Gear Size: Default Scaling: no ...... ...... Your application 'mysite' is now available. URL : http://mysite..................... SSH to : 39394949...................... Git remote: ssh://...................... Run 'rhc show-app mysite' for more details about your app. 5) Clone your site $ rhc git-clone mysite Or D:\> rhc git-clone mysite ....................... Your application Git repository has been cloned to "D:\mysite" 6) #”D:\mysite>” is the location we cloned. D:\mysite> git remote add upstream -m master git://github.com/rancavil/django-openshift-quickstart.git D:\mysite> git pull -s recursive -X theirs upstream master 7) D:\mysite> git push remote : ................ remote: Django application credentials user: admin xertefkefkt remote: Git Post-Receive Result: success ............. 8) D:\mysite>virtualenv venv --no-site-packages D:\mysite>venv\Scripts\activate.bat <venv> D:\mysite> python setup.py install creating ..... Searching for Django<=1.6 ............. Finished processing dependencies for mysite==1.0 9) Change admin password <venv> D:\mysite\wsgi\openshift> python manage.py changepassword admin password: ... Password changed successfully for user 'admin' <venv> D:\mysite\wsgi\openshift> python manage.py runserver Validating models…. 10) Git add <venv> D:\mysite> git add. <venv> D:\mysite> git commit -am"activating the app on Django / Openshift" ....... <venv> D:\mysite> git push #---------------------------------------------------------------------------------- #-----------Edit your setup.py in mysite with packages you want to install---------- from setuptools import setup import os # Put here required packages packages = ['Django<=1.6', 'lxml', 'beautifulsoup4', 'openpyxl'] if 'REDISCLOUD_URL' in os.environ and 'REDISCLOUD_PORT' in os.environ and 'REDISCLOUD_PASSWORD' in os.environ: packages.append('django-redis-cache') packages.append('hiredis') setup(name='mysite', version='1.0', description='OpenShift App', author='Tanveer Alam', author_email='xyz#gmail.com', url='https://pypi.python.org/pypi', install_requires=packages, )
These are steps that works for me: I've done some steps manually, but you can automate them later to be done with each push command. Create new django app with python-3.3 from website wizard Add mysql cartridge to app (my option is mysql) git clone created app to local add requirements.txt to root folder Add myapp to wsgi folder Modify application to refer to myapp execute git add, commit, push Browse app and debug errors with "rhc tail myapp" connect to ssh console rhc ssh myapp 10.execute this source $OPENSHIFT_HOMEDIR/python/virtenv/venv/bin/activate install missing packages if any go to app directory cd ~/app-root/runtime/repo/wsgi/app_name do migration with: python manage.py migrate create super user: python manage.py createsuperuser 15.Restart the app
This is helpful for me take a look http://what-i-learnt-today-blog.blogspot.in/2014/05/host-django-application-in-openshift-in.html
Heroku & Django: "OSError: No such file or directory: '/app/{myappname}/static'"
I have a Django app on Heroku. I am having some problems with static files (they are loading in one Heroku environment but not another), so I tried the debug command recommended here. $ heroku run python manage.py collectstatic --noinput Running `python manage.py collectstatic --noinput` attached to terminal... up, run.8771 OSError: [Errno 2] No such file or directory: '/app/{myappname}/static' Here is my settings.py, which is the same thing Heroku recommends: import os import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I get the error whether or not I actually have a directory "static" at the root level in my Git repo (tested it both ways). Any ideas?
It's looking for a folder named 'static' that's next to the settings.py, i.e. in the project folder, not at the root of the git repo. git root/ git root/{app name} git root/{app name}/settings.py git root/{app name}/static/ <- this is what you're missing Note that empty folders aren't tracked by git, so you'll have to put a blank file in there if it's empty. Alternatively, remove the STATICFILES_DIRS setting until you need it.
I just had this same problem, and here's the solution that worked for me: I changed: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) to: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'myappfolder/static'), )
#joerick's answer above is the thing. However, if you do not want to place another 'static' folder (git root/{your app}/static), you might consider changing the BASE_DIR variable that is initially supplied by django-admin makeproject: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) which is just the (git root/) directory