September 25, 2009

Setup Django with mod_wsgi on your Mac

In spirit of writ­ing this down so I don’t forget, I humbly submit this to the Inter­nets in the vain hope that it helps some­one else.

For the pur­poses of this I’m assum­ing that you have Python and Django installed. I use Mac­ports but feel free to use Home­brew or any other fine pack­age man­ager.

~ $ sudo port install apache2 mod_wsgi
cd /opt/local/apache2/conf
sudo cp httpd.conf.sample httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
Include conf/extra/httpd-vhosts.conf
NameVirtualHost *:80
 
<VirtualHost *:80>
    ServerName local.yourdomain.com
    ErrorLog "/private/var/log/apache2/local.yourdomain.com-error_log"
 
    <Directory /Users/YOUR-USERNAME-HERE/Code/wsgi_apps>
        AllowOverride All
        Options Indexes FollowSymLinks
        Order allow,deny
        Allow from all
    </Directory>
 
    WSGIDaemonProcess local.yourdomain.com processes=1 threads=1 maximum-requests=1
    WSGIProcessGroup local.yourdomain.com
 
    WSGIScriptAlias / "/Users/YOUR-USERNAME-HERE/Code/wsgi_apps/local.yourdomain.com.wsgi"
</VirtualHost>

Note: I amended the WSGI­Dae­mon­Process line above so your code would get refreshed with each new request.

The ~/Code/wsgi_apps path is arbi­trary, that’s just where I keep mine.

Many folks like to keep their .wsgi files in a /public direc­tory inside their Django project. I like to work with­out a project folder, but either way, sub­sti­tute the path to your wsgi file for /Users/YOUR-USERNAME-HERE/Code/wsgi_apps.

$ sudo apachectl configtest
Syntax OK
import site
site.addsitedir('/Users/YOUR-USERNAME-HERE/.virtualenvs/YOUR-VIRTUALENV/lib/python2.4/site-packages')
 
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysettingsmodule.local'
 
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

I’m using Ian Bicking’s vir­tualenv and Doug Hellmann’s kick-​ass vir­tualen­vwrap­per, and you should be too.

If you’re not and you’re able to ignore the cries of all the pup­pies and bun­nies you’re killing because you’re not, then you’ll want to remove the first two lines.

$ sudo apachectl start

That should be it! Go to http://​local.​your​do​main.com in your favorite browser and you should see your Django project.

Filed under: Django,Programming,Python

Next:
Previous:

Related

  • Iraê

    Very nice writeup! It helped me a lot!

    But for me one I had to append my project folder to the path, like so:

    import os, sys sys.path = ['/Users/USERNAME_HERE/code/PROJECT_NAME/'] + sys.path os.environ['DJANGO_SETTINGS_MODULE'] = ‘settings’

    Where you replace USERNAME_HERE and PROJECT_NAME by your values.

    Also in my set​tings.py file I did:

    PROJECT_PATH = os.path.abspath(os.path.dirname(file)) TEMPLATE_DIRS = (     PROJECT_PATH + ‘/templates/’, )