Deploying Django on Heroku (Mac OS X)
Heroku is a very popular Cloud PaaP (Platform as a Service) platform which allows you to deploy various applications. Heroku doesn’t charge anything to signup and has a free service upto 5 MB usage of database, that’s enough to try it out.
Heroku is majorly to Deploy Ruby, Node.js, Clojure, and Java apps. But, you can also run any type of app (like Django). In this post I’ll explain how to deploy Django project on Heroku.
I assume that you already signed-up with Heroku and configured your SSH keys with Heroku servers. If you haven’t done it already, follow these instructions – http://devcenter.heroku.com/articles/quickstart
EDIT:
Sep 29th, 2011 – Heroku now officially supports Django – http://devcenter.heroku.com/articles/django
Sep 17th, 2011 – Added `gunicorn` to make the django project production ready.
OK, Let’s get started –
Create a folder for heroku app:
mkdir heroku-django
cd heroku-django
Create a virtualenv inside the heroku app folder and activate it:
virtualenv --no-site-packages .
source bin/activate
Install django and psycopg2 packages
bin/pip install django
env ARCHFLAGS="-arch i386 -arch x86_64" bin/pip install psycopg2
bin/pip install gunicorn
Save all the local site-packages to requirements.txt file
bin/pip freeze > requirements.txt
Create a new django project naming ‘django_project’
bin/django-admin.py startproject django_project
Edit django_project/settings.py file to Uncomment admin app of our django project:
vi django_project/settings.py
# After Uncommenting .admin and .admindocs app INSTALLED_APPS in settings.py looks like this:
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',
)
Create a Process file for heroku to run:
vi Procfile
Add these two lines:
web: bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT django_project/settings.py
worker: bin/python django_project/manage.py celeryd -E -B --loglevel=INFO
Edit django_project/urls.py to add a controller for homepage and admin panel on django:
vi django_project/urls.py
Your urls.py file will have these lines after edit:
[python]from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(”,
url(r’^$’, ‘views.home’, name=’home’),
url(r’^admin/doc/’, include(‘django.contrib.admindocs.urls’)),
url(r’^admin/’, include(admin.site.urls)),
)
[/python]
Create a view for homepage:
vi django_project/views.py
Add these lines to views.py file, it just returns ‘Hello World!’ http response in plain text.
[python]from django.http import HttpResponse
def home(request):
return HttpResponse("Hello World!")
[/python]
Add virtualenv folders to .gitignore list:
cat >.gitignore <<EOF
bin/
include/
lib/
EOF
Initialize a git repository and do initial commit:
git init
git add .
git commit -m "Initial Commit"
Create a heroku app with cedar stack, note that this command automatically sets the remote server as heroku with the url to new heroku app’s git repository:
heroku create --stack cedar
# just to verify the heroku remote
git remote show heroku
Your Heroku Folder will look like this (excluding virtualenv files):
.Python
.gitignore
Procfile
django_project/__init__.py
django_project/manage.py
django_project/settings.py
django_project/urls.py
django_project/views.py
readline-6.2.1-py2.6-macosx-10.6-universal.egg/readline.so
requirements.txt
Create (or Sync) database and tables:
heroku run bin/python django_project/manage.py syncdb --app vivid-water-6038
Now, Push the django files, Procfile and requirements.txt to Heroku (master branch):
git push heroku master
Here, replace vivid-water-6038 with your heroku app name.
Congratulations! you’ve just created your first django app on Heroku:
Access from http://your-app-name-here.herokuapp.com
My Heroku app:
http://vivid-water-6038.herokuapp.com
Have fun! 🙂
Thanks!
Reference:
https://gist.github.com/1004844
Join the Hacker News Discussion:
http://news.ycombinator.com/item?id=3008106
Hey, thanks for this!
One note, correct me if I’m wrong, but one has to push first, and only then can create or sync databases (i.e. the last two steps have to be done in the opposite order). Otherwise everything went like a charm.
Hey, you are right. We have to push the django project first and then Sync the database. I’ll make the changes accordingly. Thanks!
will test it definitely! thanks!
All the best!
Cool, I had no idea this was possible. However …
The Django guys explicitly say NOT to use the built-in server in a production environment:https://docs.djangoproject.com/en/1.3/ref/django-admin/#runserver-port-or-address-port
You should instead use gunicorn: http://gunicorn.org/
Thanks Kyle! I just added gunicorn to make it production ready.
I made the changes to my blog post accordingly.
Thanks!
We made a post about production-ready Django setup on Heroku (using gunicorn) and how to exploit it to get 8 times better performance: http://www.askthepony.com/blog/2011/07/getting-django-on-heroku-prancing-8-times-faster/
Thanks for those stats Marc! That’s a very useful blogpost.
I made changes to my blog to add gunicorn workers. Thank you!
I’m seeing an error when I try to run git push heroku master:
NameError: name ‘install’ is not defined
Command /tmp/build_24cyqlmbc3y1i/bin/python2.7 -c “import setuptools;__file__=’/tmp/build_24cyqlmbc3y1i/build/distribute/setup.py’;exec(compile(open(__file__).read().replace(‘rn’, ‘n’), __file__, ‘exec’))” install –single-version-externally-managed –record /tmp/pip-i0Sx9u-record/install-record.txt –install-headers /tmp/build_24cyqlmbc3y1i/include/site/python2.7 failed with error code 1
Any advice?
That’s weird. why is it showing /tmp folder when you created a virtualenv. did you follow the instructions correctly?
Thx!
Yes, for me also showing error. I don’t know what to do? Can you Any fix for it ?
HerokuでDjangoも動くのか。知らなかった。
HerokuでDjangoも動くのか。知らなかった。
Hey, nice tut! I got the following error though when i do the last step of: heroku run bin/python django_project/manage.py syncdb –app myappname
Running bin/python django_project/manage.py syncdb attached to terminal… up, run.8sh: bin/python: not found
Do you have any idea why this is? Is my heroku gem installed wrongly?
Hey Thanks!
can you try pushing the code to heroku first and then do syncdb step? Let me know if it works.
Hey Abhinay, you are right, before running you have to push the code to heroku first and then sync and run. Thanks
i get the permission error while installing heroku :
Err:
(heroku-django)George-Kalangis-MacBook-Pro:heroku-django George$ gem install herokuERROR: While executing gem … (Gem::FilePermissionError) You don’t have write permissions into the /usr/bin directory.
try
sudo gem install heroku
I remember once reading before on this site but this one is much more interesting
apple cider vinegar benefits
Thanks! This is great. When I type:
heroku run bin/python django_project/manage.py syncdb –app myappname
I receive the following message:
Running bin/python manage.py syncdb myappname attached to terminal… ! App not found
Any guess as to what’s going on? Thanks!
Hi Jsmoxon! please check if your heroku app is created by logging into heroku.com and then try executing this command with –app option. Thanks!
Thanks, I ended up using this template from github (https://github.com/voluntas/heroku-template-django) which was very helpful.
Does anyone know about serving static files? I’m trying to link to a css stylesheet, but am not having any luck.
Thanks!
anyone did find a way to serving static files there?
I haven’t tried using static files on the Heroku. I’ll give it a try when I’ve time.
It is also possible a good way to host the static files somewhere else and referring to it from your django templates – for example: static.yourdomain.com
(heroku-django)[jaderberg@Max-Jaderbergs-MacBook-Pro heroku-django]$ bin/pip install django
Downloading/unpacking django
Downloading Django-1.3.1.tar.gz (6.5Mb): 6.5Mb downloaded
Running setup.py egg_info for package django
Installing collected packages: django
Running setup.py install for django
changing mode of build/scripts-2.6/django-admin.py from 644 to 755
changing mode of /Users/jaderberg/Sites/heroku-django/bin/django-admin.py to 755
Successfully installed django
Cleaning up…
(heroku-django)[jaderberg@Max-Jaderbergs-MacBook-Pro heroku-django]$ env ARCHFLAGS=”-arch i386 -arch x86_64″ bin/pip install psycopg2
Downloading/unpacking psycopg2
Downloading psycopg2-2.4.2.tar.gz (667Kb): 667Kb downloaded
Running setup.py egg_info for package psycopg2
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext –pg-config /path/to/pg_config build …
or with the pg_config option in ‘setup.cfg’.
Complete output from command python setup.py egg_info:
running egg_info
creating pip-egg-info/psycopg2.egg-info
writing pip-egg-info/psycopg2.egg-info/PKG-INFO
writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
writing manifest file ‘pip-egg-info/psycopg2.egg-info/SOURCES.txt’
warning: manifest_maker: standard file ‘-c’ not found
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext –pg-config /path/to/pg_config build …
or with the pg_config option in ‘setup.cfg’.
—————————————-
Command python setup.py egg_info failed with error code 1
Storing complete log in /Users/jaderberg/.pip/pip.log
Any idea what the problem is?
which operating system are you using? pg_config is installed on your system? the pg_config executable is it in your PATH env?
mac osx. just added the PATH and it works, ie:
env ARCHFLAGS=”-arch i386 -arch x86_64″ PATH=$PATH:/Library/PostgreSQL/9.1/bin/ bin/pip install psycopg2
I’m getting a problem. These are the log files from Heroku (heroku logs):
2011-09-25T14:57:27+00:00 app[web.1]: 2011-09-25 14:57:27 [7428] [INFO] Booting worker with pid: 7428
2011-09-25T14:57:27+00:00 app[web.1]: Settings file ‘/app/settings.py’ not found in current folder.
2011-09-25T14:57:27+00:00 app[web.1]: 2011-09-25 14:57:27 [7425] [INFO] Worker exiting (pid: 7425)
I syncdbed, created a superuser but it seems to be looking for the settings.py file in the wrong folder! Any ideas?
The problem was (just to be clear) that the Procfile should be two lines:
web: bin/gunicorn_django –workers=4 –bind=0.0.0.0:$PORT django_project/settings.py
worker: bin/python django_project/manage.py celeryd -E -B –loglevel=INFO
not three as it looks like in the blog post!
you forgot the git push heroku master command after the heroku create –stack cedar command. Great post!
What if you already have a local database and want to copy its information to Heroku, instead of starting a new database? The Heroku docs for this only apply to Rails, not Django.
How do you use MongoDB with Django on Heroku? It seems Heroku overrides the settings and uses Postgres, even if you configure django_mongodb_engine as the ENGINE.
I have this error
ralph@ralph-K42F:~/Biconsole/heroku$ git push heroku masterCounting objects: 11, done.Delta compression using up to 2 threads.Compressing objects: 100% (9/9), done.Writing objects: 100% (11/11), 3.51 KiB, done.Total 11 (delta 0), reused 0 (delta 0)—–> Heroku receiving push ! Heroku push rejected, no Cedar-supported app detectedTo git@heroku.com:high-mist-3096.git ! [remote rejected] master -> master (pre-receive hook declined)error: failed to push some refs to ‘git@heroku.com:high-mist-3096.git’ralph@ralph-K42F:~/Biconsole/heroku$
Python apps are detected by the presence of `requirements.txt` at the root of the repo.
Wow, great tutorial you have shared here and useful contents i got in this post.
Hie Omkar !! The tutorial was really awesome dude. I have felt that the blog was quite worthful and happy to be here.
Glad to visit this professional blog… I would love to learn more and more about technical and programming related things.. Great work!
Its really an informative post. Thanks for sharing this post. Its really a good concept chosen..
U have made my day go with such a valuable and informative blog. Really worthful being here ..
Nice blog, I am very impressed on knowing that this information is being shared here and actively discussed by these commentators here. I do want to know certain updates though. !!!
Very useful this subject I have ever read. before Keep up it
Well,nice explanation,thanks for sharing this great blog.
Love the quality and consistency of the content I keep finding on this website! I keep coming back because I keep learning while at the same time having a good time.
I am glad to found such useful post. I really increased my knowledge after read your post which will be beneficial for me.
Interesting blog. It would be great if you can provide more details about it. Thanks you.
I appreciate your work. This information is really cool and lot informative. Keep this work up and make us knowledgeable.
This article gives the light in which we can observe the reality. This is very nice one and gives indepth information.
I thank you for taking your time sharing your thoughts and ideas to a lot of readers out there.Its very typical to write such kind of article for typical topic.
Thanks for the nice blog. It was very useful for me. Keep sharing such ideas in the future as well.
You’ve nice and straightforward interface together with fantastic stuff on your blog. I also manage a personal blog and now you are in my favorite blog list. thanks for the wonderful aid and have a nice day. Free Website Directory
Please remember that I waiting for your next awesome post.
Above the review is excellent one.Each and everyday i get it interesting topic through this blog.
This is a great blog posting and very useful. I really appreciate the research you put into it.
Amazing post! i am so thankful to you! quite informative and interesting as well… appreciate your efforts!
Nice information, I would like to appreciate your good work and also would like to encourage you to keep it up.
Wow… Thanks..
Wow… Thanks.. I’m at the first time on your blog! And I like it! Thanks for sharing info. Keep up the good work.
Amazing post!
I will recommend my friends to read this. I will bookmark your blog and have my children check up here often
Specially to those who are semi naughty or semi conservative people. I guess there are a lot of things their that can be bought. rolex
Hi, when I try to sync the database, I get a bash error saying “bin/python: no such file or directory”. What am i doing wrong?
Thanks!
Help me please….
(djheroku)usuario3@hpcompaq:~/djheroku/djangoheroku$ heroku run bin/python djangoheroku/manage.py syncdb –app djangoheroku
Running `bin/python djangoheroku/manage.py syncdb` attached to terminal… failed
! App not found
Thanks for the very good summary 🙂
I’ll try it for client soon.