Today I had the task of installing a development server running the Django Python framework for one of our web developers. I learned a few things and I figured a quick tutorial might help someone else out. None of this covers new ground, but perhaps another telling of the story will help someone out there. I started from scratch, with a basic install of Ubuntu 7.04 Server Edition. I did not choose any extra packages, such as the LAMP option or DNS server. If you are starting off with a LAMP server already installed, or a different version, the steps will be similiar, but you may need to adapt some commands to get them to work.
Install Apache, Mod_Python, MySQL and MySQLdb. MySQLdb is the database bindings for MySQL. Django also supports PostgreSQL, Oracle and SQLite. If you choose to use a different database server, be sure to install the appropriate Python bindings.
sudo apt-get install apache2 libapache2-mod-python sudo apt-get install mysql-server python-mysqldb
At this point you have a couple of options. You could “apt-get install” a Django package, install an official release or install the development version. I chose to install the development version because it contains the latest bug fixes and features. We’ll be checking out the latest version from its Subversion repository. You’ll want to be in your home directory when you do this.
cd ~/ svn co http://code.djangoproject.com/svn/django/trunk/ django_src
Python won’t recognize Django unless it is installed in the “site-packages” directory, so instead we just create a symbolic link to the source code in our home directory. Run the first command to find out the path to your “site-packages” directory. Then use it in the second command, in place of “YOUR-DIR”. Lastly, copy the django-admin.py file into /usr/local/bin so that we don’t have to qualify the command with the full path to the file.
python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" ln -s `pwd`/django_src/django YOUR-DIR/django sudo cp ~/django_src/django/bin/django-admin.py /usr/local/bin
Next we need to create some directories that Django will use. Once again, create these under your home directory.
cd ~/ mkdir django_projects mkdir django_templates mkdir media
Then we need to create some symbolic links in your webroot. The default webroot for an Apache2 installation on Ubuntu is /var/www. We are going to create a link to the media folder in your home directory, and a link to the admin_media folder which is provided in the Django source code.
cd /var/www sudo ln -s ~/media media sudo ln -s ~/django_src/django/contrib/admin/media admin_media
Move into your Django projects directory that we just created. We will be starting a new project using Django’s command line utility. This will give us a basic directory structure and the necessary configuration files. In my example I named the project “myproject.” Feel free to choose any name, as long as it does not conflict with any built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or site (which conflicts with a built-in Python package).
cd ~/django_projects django-admin.py startproject myproject
Edit the myproject/settings.py file and change the following sections:
6 7 8 9 10 | ADMINS = ( ('Your Name', 'your_email@domain.com'), ) |
12 13 14 15 16 17 18 19 20 21 22 | DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'django_databae' # Or path to database file if using sqlite3. DATABASE_USER = 'you' # Not used with sqlite3. DATABASE_PASSWORD = 'yourpassword' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. |
19 20 21 22 23 24 25 26 27 28 29 | # Local time zone for this installation. Choices can be found here: # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE # although not all variations may be possible on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' |
69 70 71 72 73 74 75 | TEMPLATE_DIRS = ( "/home/YOUR_USERNAME/django_templates" # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". ) |
36 37 38 39 40 41 42 43 44 45 46 | # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '/home/YOUR_USERNAME/media/'# URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = 'http://yourdomain.com/media/' |
45 46 47 48 49 50 51 | # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/admin_media/' |
76 77 78 79 80 81 82 83 84 85 86 87 88 | INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', ) |
After making all those changes to the configuration we need to synchronize the Django database. You’ll also get a prompt asking you if you’d like to create a superuser account for the authentication system. Go ahead and do that.
django-admin.py syncdb
Edit the URL configuration file and uncomment the admin line. This will allow you to access the admin section later.
nano ~/django_projects/myproject/urls.py
1 2 3 | # Uncomment this for admin: (r'^admin/', include('django.contrib.admin.urls')), |
In Apache2 on Ubuntu, changes to the Apache configuration are done to the /etc/apache2/httpd.conf file. We are going to configure mod_python to handle requests for the root of the site and give control to Django. However, Django doesn’t serve media files itself; it usually expects you to have a different webserver serving these files. In our case though, we want Apache to handle it, so we need to turn off mod_python for some parts of the site. You will also need to do this if you have any other folders or scripts that you want excluded from Django’s control. In my example, I have phpMyAdmin, my media folders and any URL that ends with .jpg, .gif or .png be excluded.
When deploying Django sites on mod_python, you’ll need to restart Apache each time you make changes to your Python code. However, since I’m using this as a development server, I discovered a way to avoid the hassle of having to restart the server each time. At the top of my httpd.conf, I have the line MaxRequestsPerChild 1. This forces Apache to reload everything for each request. Do not use this setting on a production server!
The only other lines you need to change are in the first <Location> block. Change “myproject.settings”, if you are using a different name for your project. Then below that be sure to change the PythonPath to point to the django_projects folder in your home directory.
sudo nano /etc/apache2/httpd.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | MaxRequestsPerChild 1 <location "/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE myproject.settings PythonPath "['/home/YOUR_USERNAME/django_projects'] + sys.path" </location> <location "/media"> SetHandler None </location> <location "/admin_media"> SetHandler None </location> <location "/phpmyadmin"> SetHandler None </location > <locationmatch "\.(jpg|gif|png)$"> SetHandler None </locationmatch> |
sudo /etc/init.d/apache2 restart
You can now view your new Django website by visiting the root of the website you installed it at - http://yourdomain.com/ . You should see a Page not Found (404) error message generated by Django. Congratulations! Everything is working. You can also go to http://yourdomain.com/admin/ and log in with the superuser you created earlier.
Now that you’re done with the easy part, all thats left is to get started writing your Django apps. There is a tutorial on the official Django website that will walk you through creating an application.
35 Responses
Italo Maia
August 26th, 2007 at 7:45 pm
1Not working. Got this error : directive requires additional arguments .
And this line ain’t right : sudo nano /etc/apache/http.conf
Jeff
August 26th, 2007 at 8:00 pm
2Sorry about that, that is a typo. That line should read –
sudo nano /etc/apache2/httpd.conf
I have updated this blog post.
When are you getting that error message? Heres something you can try -
Double check your Project name. In my example I used “myproject” as the name. If you were following a different tutorial, it may be “mysite” or something similar. Double check that you edit the httpd.conf and use the correct project name in the mod_python configuration.
trent
August 30th, 2007 at 8:24 am
3Thanks for the help with getting django running, I’ve got it going now and the django docs are excellent learning tools! My ultimate goal is to build my own blog. I found a couple tutorials but none supply comments or rss.. I guess that shouldn’t be too hard to add in if I can do the rest!
Thanks for all of your help!
Ed Ad
August 30th, 2007 at 5:19 pm
4I also got the error message of Italo. The location tag should be:
. The empty locations should be removed and then it works.
Jeff
August 30th, 2007 at 8:22 pm
5You’ve found another typo I made. For some reason, when I copied the text out of my httpd.conf from the terminal into this blog post, it left out pieces. I’ve updated my post to show the correct httpd.conf now. Basically the first Location directive is for “/” which sets up django to take over for the website root, then the other following location directives exclude the media, admin media, phpmyadmin directories, and also any image file. Once again, sorry about the typo’s.
sneaker
September 1st, 2007 at 3:17 pm
6Thanks! This was helpful — I was struggling with getting the django admin to get served up by apache and following your steps seems to have resovled the issue.
neophyte
September 2nd, 2007 at 10:57 am
7Jeff,
Great how-to! Thank you for helping out newbies such as myself.
I did run into a problem.
When I attempt to create a new django project, I get the following error:
Traceback (most recent call last):
File “/usr/local/bin/django-admin.py”, line 2, in
from django.core import management
ImportError: No module named django.core
I have been unable to resolve this issue. Any clues would be greatly appreciated.
neophyte
September 2nd, 2007 at 12:54 pm
8Jeff,
Please disregard the previous post. I failed to set the correct PYTHON path in my .bashrc file.
export PYTHONPATH=”.:$HOME/Web/django_project
Thanks again!
Riccardo
September 6th, 2007 at 6:37 am
9Jeff,
really great How-to!
But i get this error
“EnvironmentError: Environment variable DJANGO_SETTINGS_MODULE is undefined.”
when I syncdb
Any ideas would be greatly appreciated
Jeff
September 6th, 2007 at 3:54 pm
10Try setting it in your shell before running syncdb –
export DJANGO_SETTINGS_MODULE=myproject.settings
If you’re using a different project name, be sure to change ‘myproject’ above to whatever your project name is.
Andre
September 9th, 2007 at 2:53 pm
11I had the same error as Ricardo and then I did
export DJANGO_SETTINGS_MODULE=myproject.settings
I used the same project name
Then once again I tried
django-admin.py syncdb
and now I get a different error.
EnvironmentError, “Could not import settings ‘%s’ (Is it on sys.path? Does it have syntax errors?): %s” % (self.SETTINGS_MODULE, e)
EnvironmentError: Could not import settings ‘myproject.settings’ (Is it on sys.path? Does it have syntax errors?): No module named myproject.settings
I don’t know what to do. Please help me out.
Tim
September 10th, 2007 at 8:12 am
12Andre,
I had the same problem, solved it by running these 2 commands from the new projects directory eg (/home/YOUR_USERNAME/django_projects/myproject/)
export DJANGO_SETTINGS_MODULE=settings
export PYTHONPATH=$PWD
$PWD is a variable for the current directory. You can also set this 2nd command permanently in your .bashrc file as neophyte has done above.
Hope it helps.
Tim
September 10th, 2007 at 8:41 am
13There’s another easier way to syncdb as shown in the tutorial linked above from the Django homepage.
Again from the project directory, use this command:
python manage.py syncdb
This uses manage.py to setup the environment correctly so all the paths are pointing in the right place.
See here for why you would want to use each method:
http://www.djangoproject.com/documentation/django-admin/
HSM
September 20th, 2007 at 12:34 pm
14Hi Jeff,
Thanks for a great tutorial.
Everything works and the 404 page even looks pretty. But when I access the admin page (localhost/admin), the css file does not load (I’m a novice so I may not be describing the symptom accurately). The page looks like plain html with no formatting whatsoever. Just plain black font on white page, no indentation, everything left aligned.
Anyhelp would be appreciated.
Thanks
Hani
HSM
September 20th, 2007 at 12:55 pm
15Hi Jeff,
Figured it out. My bad. typo in the settings.py for ADMIN_MEDIA_PREFIX.
Once again, great howto.
Thanks,
Hani
Jeff V
September 29th, 2007 at 6:55 pm
16I love your tutorial, i run into one problem when I try to sync the DB. Im pretty sure somthing isnt set correctly in the __init__.py file… Let me know what you think.
File “/usr/local/bin/django-admin.py”, line 5, in
management.execute_from_command_line()
File “/usr/lib/python2.5/site-packages/django/core/management.py”, line 1563, in execute_from_command_line
from django.utils import translation
File “/usr/lib/python2.5/site-packages/django/utils/translation/__init__.py”, line 3, in
if settings.USE_I18N:
File “/usr/lib/python2.5/site-packages/django/conf/__init__.py”, line 28, in __getattr__ self._import_settings()
File “/usr/lib/python2.5/site-packages/django/conf/__init__.py”, line 55, in _import_settings
self._target = Settings(settings_module)
File “/usr/lib/python2.5/site-packages/django/conf/__init__.py”, line 83, in __init__
raise
EnvironmentError, “Could not import settings ‘%s’ (Is it on sys.path? Does it have syntax errors?): %s” % (self.SETTINGS_MODULE, e)
EnvironmentError: Could not import settings ‘myproject.settings’ (Is it on sys.path? Does it have syntax errors?): No module named myproject.settings
Wahoo
October 6th, 2007 at 3:38 pm
17Thank you for sharing!
Dan
October 20th, 2007 at 6:10 pm
18Thanks for the tutorial! I have it working, now I just have to learn to use it.
Aydin
January 5th, 2008 at 2:30 pm
19Thanks for the great tutorial!
I can’t do the sync operation because I get the following:
aydin@aydin-ubuntu:~/django_projects$ django-admin.py syncdb
Traceback (most recent call last):
File “/usr/local/bin/django-admin.py”, line 5, in
management.execute_from_command_line()
File “/usr/local/lib/python2.5/site-packages/django/core/management.py”, line
1571, in execute_from_command_line
action_mapping[action](int(options.verbosity), options.interactive)
File “/usr/local/lib/python2.5/site-packages/django/core/management.py”, line
486, in syncdb
from django.db import connection, transaction, models, get_creation_module
File “/usr/local/lib/python2.5/site-packages/django/db/__init__.py”, line 11,
in
backend = __import__(’django.db.backends.%s.base’ % settings.DATABASE_ENGINE
, {}, {}, [''])
File “/usr/local/lib/python2.5/site-packages/django/db/backends/mysql/base.py”
, line 12, in
raise ImproperlyConfigured, “Error loading MySQLdb module: %s” % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No mo
dule named MySQLdb
any help would be appreciated…
Aydin
January 5th, 2008 at 2:50 pm
20as a followup to this it seems that I don’t have MySQL-python…
everytime I try to install this, I get the following:
aydin@aydin-ubuntu:~/Desktop/MySQL-python-1.2.2$ python setup.py build
Traceback (most recent call last):
File “setup.py”, line 5, in
import ez_setup; ez_setup.use_setuptools()
File “/home/aydin/Desktop/MySQL-python-1.2.2/ez_setup.py”, line 85, in use_setuptools
import setuptools; setuptools.bootstrap_install_from = egg
zipimport.ZipImportError: can’t decompress data; zlib not available
Aydin.
Jeff
January 5th, 2008 at 6:00 pm
21One of the first steps in the tutorial is to install the python-mysql bindings. It sounds like you may have skipped over that step, or have a problem with it.
Try the command
sudo apt-get install python-mysqldb
and tell me what happens.
Aydin Mirzaee
January 6th, 2008 at 7:48 am
22hi Jeff,
thanks for you comment… I struggled for hours to figure out what was wrong… I did also try the command you suggested… I just got a message saying I had the latest version already…
anyhow, at the end of the day, I just reinstalled ubuntu (thankfully, with VMWare, this only took 5 minutes)… then I did everything in accordance with this tutorial and now django is up and running!
Thanks so much!
This website Rocks!
Aydin.
Muhamad Abdul Hay
January 24th, 2008 at 1:36 am
23Hi,
I got this error
abdhay@star:~/django_projects$ django-admin.py startproject smsproject
Traceback (most recent call last):
File “/usr/local/bin/django-admin.py”, line 2, in
from django.core import management
ImportError: No module named django.core
Help!
Jeff
January 25th, 2008 at 9:24 pm
24Muhamad Abdul Hay,
It sounds like its not recognizing your django.core. This is usually because it can’t find the source in the “site-packages” directory. Just create a symbolic link to the source code in our home directory.
Use this command to find the correct directory. Copy its output and replace “YOUR-DIR” in the second command with it.
python -c “from distutils.sysconfig import get_python_lib; print get_python_lib()”
ln -s ~/django_src/django YOUR-DIR/django
Matthias
March 8th, 2008 at 2:50 pm
25Django is already a package in Ubuntu
Try
sudp apt-get install python-django
it might save you doing the first couple of steps in this tutorial.
Jeff
March 10th, 2008 at 9:04 am
26@Matthias
You are absolutely correct. I mentioned in my blog post that installing Django as a package is one of many options. I chose to install by checking out the latest version from subversion. This way it contains the latest bug fixes and features. Upgrading is also then just as easy as issuing the ’svn update’ command.
hollerith
April 22nd, 2008 at 5:58 pm
27Great post - apache is hell for me (and Guido too apparently)
@Matthias - this is true but if you use the ubuntu package bear in mind that django-admin.py becomes django-admin due to a debian standard for /usr/local/bin.
If you are new to django and are following the documentation closely then some might prefer to use subversion trunk. Is that a ‘bad thing’?
Cerberius
May 1st, 2008 at 12:57 pm
28Great Tutorial, i’m on ubuntu 8.04 and i followed the tutorial step by step and when i access my the root of my website i see a Page not Found (404) error message generated by Django, but when i try to get into the admin i see a error message “Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.”
Any help would be appreciated.
Thanks in advanced.
Hoora
May 5th, 2008 at 10:08 am
29Thanks for the tutorial, came in handy!
Now that I got everything else running I can’t get django to load css for the django admin. Getting somewhat frustrated, hope someone can help me here. Tried to chmod 777 (never do that) the admin_media folders if there was some user restriction but no, it didn’t help. I’ve also checked the myproject/settings.py many times and it should be ok…
MEDIA_ROOT = ‘/home/myusername/media/’
MEDIA_URL = ‘http://localhost/media/’
ADMIN_MEDIA_PREFIX = ‘/admin_media/’
I’ve tried many things allready and I would appreciate any suggestions where to find the problem? On the django admin page the Firefox is looking for the css from the folder http://localhost/admin_media/css/login.css (which should be right, rite?) and it shows 404 error for the css in the firefox web developer addon.
The link in the admin media login htmlpage goes like this:
link rel=”stylesheet” type=”text/css” href=”/admin_media/css/login.css” /
Am I missing something here? Isn’t this the place to look for it? What else should I check? For me it seems like the apache2 doesn’t hop in to serve the css files for some reason even though phpmyadmin works fine.
Hoora
May 5th, 2008 at 10:21 am
30I just needed to start the server manually after syncdb with:
python manage.py runserver
Again, thanks for the tutorial. Btw, I installed it on the 8.04 ubuntu server edition.
Darthur
May 28th, 2008 at 7:09 pm
31Great Tutorial, but I keep getting stuck at the syncdb step. This is the latest error, but I have no idea what it means, and if I try sudo then the DSM not defined error comes up:
File “/usr/lib/python2.5/site-packages/django/db/backends/mysql/base.py”, line 188, in _cursor
self.connection = Database.connect(**kwargs)
File “/var/lib/python-support/python2.5/MySQLdb/__init__.py”, line 74, in Connect
return Connection(*args, **kwargs)
File “/var/lib/python-support/python2.5/MySQLdb/connections.py”, line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, “Access denied for user ‘username’@'localhost’ (using password: YES)”)
Thanks!
-D
Jeff
May 29th, 2008 at 12:07 am
32From that last line, it would seem the database is rejecting your username and password.
Check lines 12-18 of the myproject/settings.py file. This is where you setup which database to use, and the username and password for it. Verify its the correct info before running syncdb.
enej
July 8th, 2008 at 11:56 pm
33great tutorial
I think anyone reading this should also know that its a good idea to check if you installed django properly
by typing python install django
Pavel
September 2nd, 2008 at 2:05 am
34When I try to restart apache2, I have this erro:
Syntax error on line 187 of /etc/apache2/apache2.conf: Syntax error on line 30 of /etc/apache2/httpd.conf: directive missing closing ‘>’
What should I do to fix it?
django - :: Adictos.cl :: Tu Vicio en Internet
September 3rd, 2008 at 8:33 pm
35[...] quien sabe instalar las librerias de django en ubuntu necesito hacer y trabajo pa taller 2 Howto install Django on Ubuntu 7.04 Feisty Fawn using Mod_Python » JeffBaier.com esta en ingles pero lo tradices con este link traduccion webbbs __________________ SOLO CON [...]
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Other
About Me
My name is Jeff Baier and I'm a freelance computer consultant. Some of my jobs include web design, programming and timing track meets.
My Status
Random photos
View more photos >
Recent Posts
Recent Comments
Links
JeffBaier.com © 2007 All rights reserved.