Installing Django with Apache and mod_wsgi on Ubuntu 10.04

Step by step instructions for installing Django with Apache and mod_wsgi on Ubuntu 10.04.

PART 1 – Prepare the server

Update the server

> sudo apt-get update
> sudo apt-get upgrade

Install Apache and mod_wsgi

> sudo apt-get install apache2 libapache2-mod-wsgi

Install setup tools and pip

> sudo apt-get install python-setuptools
> sudo apt-get install python-pip

Install Django

> sudo pip install django

Create a folder for storing our sites

I’ll be placing our sites in the /srv/www directory. The /srv directory should already exist so we just need to create the /www directory

> sudo mkdir /srv/www

PART 2 – Add host entries for testing

We will set up two domains for testing the configuration
- one for testing that WSGI is working, and
- one for testing that Django is working.

My test virtual machine’s IP address is 172.16.52.130 so I’ll set up the following in my local hosts file (not on the server)

> sudo nano /etc/hosts

And add the following

172.16.52.130    djangoserver
172.16.52.130    wsgi.djangoserver
172.16.52.130    hello.djangoserver

PART 3 – Test WSGI is working

Create our wsgi test site content

> sudo mkdir /srv/www/wsgi
> sudo nano /srv/www/wsgi/app.wsgi

And add the content

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'
 
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
 
    return [output]

Create a new apache site

> sudo nano /etc/apache2/sites-available/wsgi

And add the content

<VirtualHost *:80>
 
    ServerName wsgi.djangoserver
    DocumentRoot /srv/www/wsgi
 
    <Directory /srv/www/wsgi>
        Order allow,deny
        Allow from all
    </Directory>
 
    WSGIScriptAlias / /srv/www/wsgi/app.wsgi
 
</VirtualHost>

And activate the site

> sudo a2ensite wsgi
> sudo /etc/init.d/apache2 reload

Then open your web browser and browse to

http://wsgi.djangoserver

You should see a ‘Hello World!’ message

PART 4 – Test Django is working

Create a new Django site

> cd /srv/www
> sudo django-admin.py startproject hello

Create a wsgi file for the site

> sudo mkdir /srv/www/hello/apache
> sudo nano /srv/www/hello/apache/django.wsgi

And add the content

import os
import sys
 
path = '/srv/www'
if path not in sys.path:
    sys.path.insert(0, '/srv/www')
 
os.environ['DJANGO_SETTINGS_MODULE'] = 'hello.settings'
 
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Create a new apache site

> sudo nano /etc/apache2/sites-available/hello

And add the content

<VirtualHost *:80>
 
    ServerName hello.djangoserver
    DocumentRoot /srv/www/hello
 
    <Directory /srv/www/hello>
        Order allow,deny
        Allow from all
    </Directory>
 
    WSGIDaemonProcess hello.djangoserver processes=2 threads=15 display-name=%{GROUP}
    WSGIProcessGroup hello.djangoserver
 
    WSGIScriptAlias / /srv/www/hello/apache/django.wsgi
 
</VirtualHost>

And activate the site

> sudo a2ensite hello
> sudo /etc/init.d/apache2 reload

Then open your web browser and browse to

http://hello.djangoserver

You should see the Django default installation message.

Notes

NOTE 1 – Running in daemon mode

Our test Django site is configured to run in daemon mode – because of these two lines:

WSGIDaemonProcess hello.djangoserver processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup hello.djangoserver

So if we modify the code then rather than restarting apache we can just touch the wsgi file and the changes will be picked up:

> sudo touch /srv/www/hello/apache/django.wsgi

NOTE 2 – Specify the application module name

It appears to be a good idea to specify the application module when specifying the DJANGO_SETTINGS_MODULE. So rather than writing this:

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

We should write this:

os.environ['DJANGO_SETTINGS_MODULE'] = 'hello.settings'

Useful Commands

Error log file

If you get errors, check the apache log file

> tail /var/log/apache2/error.log

Test using development mode

If your app does not seem to be working using wsgi, then check if it is working via the development server.

> cd /srv/www/hello
> python manage.py runserver 0:8080

The in your web browser go to

http://hello.djangoserver:8080

References

An improved WSGI script for use with Django.
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html

Modwsgi – Integration With Django
http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango

How do I stop getting ImportError: Could not import settings ‘mofin.settings’ when using django with wsgi?
http://stackoverflow.com/questions/1411417/how-do-i-stop-getting-importerror-could-not-import-settings-mofin-settings-whe

Configuration problems with django and mod_wsgi
http://stackoverflow.com/questions/2587251/configuration-problems-with-django-and-mod-wsgi

This entry was posted in Django and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

37 Comments

  1. Mike
    Posted January 8, 2011 at 6:42 pm | Permalink

    Great walk through! Thanks for doing this.

    Helped me get up and running quickly so now I can play around with Django

  2. Jason
    Posted January 21, 2011 at 1:48 pm | Permalink

    Thanks for this great tutorial. It was my first time using mod_wsgi and I got the Django app installed on my remote server with everything running 100%. Well done on this great article.

  3. Posted March 8, 2011 at 1:56 pm | Permalink

    Thanks Kevan.

    This post is very helpful!!!!!

  4. Chris
    Posted March 14, 2011 at 9:22 am | Permalink

    Thanks so Much! This was Exactly what I needed to know for my Django/Apache project. I’m running on andLinux over Windows XP.

  5. Daniel
    Posted March 19, 2011 at 5:51 pm | Permalink

    Thank you very much Kevan! This is a great an clear manual to get things work on Ubuntu (10.10 in my case). Very helpful!!

  6. Mike Sanders
    Posted March 23, 2011 at 12:46 pm | Permalink

    Thanks man! One of the best and goal-oriented tutorials on this topic. I’m merry as a lark now to have a running DJANGO on my UBUNTU!

  7. Gonzalo
    Posted June 30, 2011 at 6:55 pm | Permalink

    Hi, thanks for the tutorial, it was very helpfull!!!. But when i try to install this configuration in a Debian Lenny (instaling apache2 and libapache2-mod-wsgi) and restart apache it throw me

    Syntax error on line 7 of /etc/apache2/httpd.conf:
    Invalid command ‘WSGIScriptAlias’, perhaps misspelled or defined by a module not included in the server configuration
    Action ‘configtest’ failed.
    The Apache error log may have more information.
    failed!

    /etc/apace2/httpd.conf:

    DocumentRoot /var/www/proyect

    Order allow,deny
    Allow from all

    WSGIScriptAlias / /var/www/proyect/apache/django.wsgi

    ServerName localhost

    SetHandler None

    SetHandler None

    Alias /media /var/www/media
    Alias /proyect /var/www/proyect

    Any idea?.

    Thanks againg

  8. Posted June 30, 2011 at 7:14 pm | Permalink

    Hi Gonzalo, looks like there might occasionally be a problem installing mod_wsgi on Debian Lenny. Have a look at http://almad.nejsem.in/blog/2010/6/9/articles/invalid-command-wsgiscriptalias-debian-lenny/ which suggests reinstalling mod_wsgi (copied here for reference):

    dpkg –purge –force-all libapache2-mod-wsgi
    apt-get install libapache2-mod-wsgi

  9. Gonzalo
    Posted July 1, 2011 at 5:14 pm | Permalink

    Hi Kendal, thanks very much. I was thinking in reinstall mod_wsgi, but finally i found my mistake. I’m install it in multiple servers and in that server i forget to create /var/www/proyect/apache/django.wsgi file.

    Thanks!!

  10. Posted July 17, 2011 at 3:11 am | Permalink

    Thanks very much for taking the time to put this together… what a great resource.

    It would’ve taken me ages to figure all of this out. I’m loving Python and Django… the linux/server/deployment bit is really the only frustrating part.

    Thanks again.

  11. Posted August 4, 2011 at 7:14 pm | Permalink

    Hi Kevan,

    Thanks for the great tutorial. Now, i have a fully functioning server with django, apache and mod_wsgi installed. This tutorial delivers what it promises. Helped a lot. Great work.

    Cheers,
    Akshar

  12. Danny Goodall
    Posted August 8, 2011 at 4:24 pm | Permalink

    Excellent walk-through. Took a lot of the pain away if deploying Django to EC2.

    Thanks!

  13. Percila
    Posted August 19, 2011 at 2:10 pm | Permalink

    Bless You Kevan!!! av learnt so much about deploying Django just from these few steps. thanx so much

  14. rafael
    Posted August 31, 2011 at 7:32 pm | Permalink

    the wsgi.djangoserver works, but when I enable the hello.djangoserver,
    everything stops working, even the wsgi.djangoserver sites outputs a 500 Internal Server Error. When I disable the hello site the wsgi.djangoserver works again.

    I have triple-checked all my files but I havent found anything.

    when I reload apache2 I get the errors:
    apache2:could not reliablydetermine the server’s fully qualified domain name, using 192.168.10.90 for ServerName

    HELP

  15. Posted August 31, 2011 at 8:23 pm | Permalink

    Hi Rafael, is there any error message showing up in the apache error log file? For a default install it should be in /var/log/apache2/error.log

  16. rafael
    Posted August 31, 2011 at 8:45 pm | Permalink

    [error] [client 192.168.10.3] mod_wsgi (pid=25250): target WSGI scripy ‘/srv/hello/apache/django.wsgi’ cannot be loaded as Python module.

    [error] [client 192.168.10.3]mod_wsgi (pid=25250): Exception occured processing WSGI script ‘/srv/www/hello/apache/django.wsgi

    [error] [client 192.168.10.3]Traceback (most recent call last):

    [error] [client 192.168.10.3]File “/srv/www/hello/apache/django.wsgi” line 10 in

    [error] [client 192.168.10.3]import django.core.handler.wsgi
    [error] [client 192.168.10.3]ImportError: No module named handler.wsgi

    can’t start anything with that.. “Cannot be loaded as a Python Module”, sounds a bit guilty to me!

  17. Posted August 31, 2011 at 8:54 pm | Permalink

    Looks like the wsgi module is missing or has a problem. Try the following:

    > sudo apt-get install libapache2-mod-wsgi

  18. rafael
    Posted August 31, 2011 at 9:00 pm | Permalink

    the module is already installed but I did what you said, then reloaded my apache server and nothing happened. We get the same errors.

  19. rafael
    Posted August 31, 2011 at 9:01 pm | Permalink

    I am actually using ubuntu server 11.04, is that maybe the issue?

  20. Posted August 31, 2011 at 10:29 pm | Permalink

    It could be a version compatibility problem with python and the wsgi module. Find your mod_wsgi.so file and run the following command:

    > ldd mod_wsgi.so

    The version of python in the output should match the actual version of python you have installed.

    Otherwise, try posting a message to the mod wsgi group. Would be great to know if you find a solution.

    http://groups.google.com/group/modwsgi

  21. Posted September 3, 2011 at 7:34 am | Permalink

    Great Tutorial, all worked easy and fine. Thanks a lot!

  22. Chris
    Posted September 7, 2011 at 11:42 pm | Permalink

    This is the most intuitive Django + Mod WSGI tutorial I’ve found so far. Great job. Now if only the standard Django docs were this easy to understand…

  23. Posted September 22, 2011 at 2:03 pm | Permalink

    I think this is the best Django+mod_wsgi tutoriol.

    Hint: For ubuntu “sudo django-admin.py startproject hello” int work
    Use “sudo django-admin startproject hello” ;)

  24. Posted November 22, 2011 at 8:52 am | Permalink

    Just received an email from Dave Parizek on this entry. Copying his message here in case it helps others. Many thanks Dave.

    Hi:

    In your article here:

    http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/

    you need to tell people to remove any default files in

    /etc/apache2/sites-enabled

    I could not get wsgi test to work until I noticed a default file in sites-enabled was setting a different document root than I wanted.

    Thanks!

  25. Dave
    Posted December 1, 2011 at 6:20 am | Permalink

    This is a great resource, many thanks Kevan. Everything followed to the tee and worked immediately.
    One thing I must ask though : I’m somewhat of a newbie in this whole arena of Django and WSGI (although have been working with WAMP/LAMP for nigh on 15 years). I’ve been given a django project which is currently being run under django’s own HTTP service (currently running via a console command as python manage.py runserver my_IP_Address:8000) but I understand that to take that and then host it in a ‘production’ environment I should be using Apache2 and MOD-WSGI.
    Is there an easy way of taking your notes eloquently written here and then applying them to a django project already coded, assuming the project has been written using normal framework filenames and structure?

  26. Posted December 1, 2011 at 10:29 am | Permalink

    Hi Dave, I’m not an expert in production deployment so don’t want to give you any misleading info. Probably best to post this question the Django user group.

    https://groups.google.com/forum/#!forum/django-users

    All the best with your project.

  27. Posted March 28, 2012 at 11:44 pm | Permalink

    Email received from Diego ( kobylkin.com )

    Kevan,

    I am referring to your walkthrough http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/

    It did not work for me on the clean install. I was getting the following error: ImportError: Could not import settings ‘hello.settings’ (Is it on sys.path?): No module named hello.settings

    One other commenter has had the same problem.
    I had to change my django.wsgi to this:

    import os
    import sys

    sys.path.insert(0,os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2]))
    os.environ['DJANGO_SETTINGS_MODULE'] = ‘testbed.settings’

    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()

    This is the string that I have added instead your code there:
    sys.path.insert(0,os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2]))

    Pls. consider adjusting your post as the comments are closed. Hope this will save a few hours to othere people trying out your otherwise very usefull walkthrough.

    Bests,
    Diego

  28. ljfais
    Posted June 15, 2012 at 10:22 am | Permalink

    Thanks a lot this save me time

  29. Chris Handy
    Posted June 17, 2012 at 1:57 pm | Permalink

    Just to say thanks for the welcome info. First time I set up Django + Apache and this was hands down the best info I found. I especially like the fact that you get wsgi part working first, since this caused me a bit of a problem on my particular machine that I was able to trace due to your article. Kudos!

  30. Paul Smith
    Posted June 20, 2012 at 7:19 pm | Permalink

    To avoid the error:
    ImportError: Could not import settings ‘hello.settings’ (Is it on sys.path?): No module named hello.settings

    Remove the three lines in django.wsgi that relate to setting the path and simply replace them with:
    sys.path.append('/srv/www')
    sys.path.append('/srv/www/hello')

  31. Kal
    Posted June 23, 2012 at 7:12 am | Permalink

    This was by far the best tutorial I have seen for this. Btw, small difference for me. In the virtual host files, where you have “DocumentRoot /srv/www/hello”, I had to put one more /hello at the end of it. Because the settings.py file was in that folder. Maybe because of a newer version? I’m not sure.

  32. Posted July 28, 2012 at 3:13 pm | Permalink

    Thanks for tutorial. Very clear installation.

    Very useful comments if you have 500 Server Error with “ImportError: Could not import settings ‘hello.settings’ (Is it on sys.path?): No module named hello.settings”.

    http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/#comment-1646

    or

    http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/#comment-1658

  33. Yansong
    Posted August 28, 2012 at 8:33 pm | Permalink

    In the /srv/www/hello/apache/django.wsgi the path you add should be ‘/srv/www/hello’

  34. fabske
    Posted September 12, 2012 at 8:43 pm | Permalink

    Hello :)

    I try to set up django on my debian wheezy and tried PART 4 – Test Django is working
    Create a new Django site:

    django-admin.py startproject hello
    Traceback (most recent call last):
    File “/usr/local/bin/django-admin.py”, line 2, in
    from django.core import management
    File “/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py”, line 54
    except ImportError,e:
    ^
    SyntaxError: invalid syntax

    Does somebody know what the problem ist??

  35. Posted October 13, 2012 at 11:50 am | Permalink

    Thank you Thank you Thank you Thank you Thank you Thank youThank you :) :):):)

    You saved me :)

  36. Csaba
    Posted November 25, 2012 at 9:33 pm | Permalink

    Hi,

    thanks for this tutorial. I’ m developing something a couple of months ago, and i wanted to bind it now to apache2. After this tutorial i got some import error, and – for me – surprisingly it started to work, when i removed my 2 appnames from the INSTALLED_APPS , but i wouldn’ t think it’ s the right solution. Any idea how should i set up the wsgi file to work with my apps if they’ re also in the INSTALLED_APPS ? Or any hint how should i write my application to work with this tutorial’ s files?

    Thanks.

  37. pjvr
    Posted November 30, 2012 at 2:54 pm | Permalink

    Thanks Kevin,

    Awesome post!

    I’m doing a deploy to EC2, and I also had trouble getting the wsgi “hello world” to work, until I saw that a default file in /etc/apache2/sites-enabled was hijacking the server.

    Thanks much ;)

4 Trackbacks

  1. [...] This guide shows you how to install Django with Apache and mod_wsgi on Ubuntu 10.04 More here [...]

  2. By Installing Django on Ubuntu 10.04 LTS on November 22, 2011 at 6:23 pm

    [...] Mostly this article came from below, but I added to it: http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ Django, Programming, [...]

  3. [...] Googling couple times, I’ve found some interesting article, http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ i’ve doing that on my local machine, and everything goes well. but How on [...]

  4. [...] 참고한곳 http://blog.stannard.net.au/2010/12/11/installing-django-with-apache-and-mod_wsgi-on-ubuntu-10-04/ This entry was posted in Web and tagged apache, django, mod_wsgi, ubuntu, wsgi by naaveh. [...]