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 server software
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
Install the Django source code
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
Create Django’s directories
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
Create a Django project
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:
- Uncomment and change the ADMINS setting
ADMINS = ( ('Your Name', 'your_email@domain.com'), ) - Enter your database settings. You will need your database, username and password. Most likely your database server is running on the same server, so leave DATABASE_HOST blank.
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.
- Change your timezone if necesary.
# 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'
- Point Django at the template directory we created.
TEMPLATE_DIRS = ( "/home/YOUR_USERNAME/django_templates" # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". ) - Do the same thing for the media url and directory we created earlier.
# 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/'
- Set the admin media directory that we created in your webroot
# 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/'
- And finally, add the admin application to your install applications
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. Youll also get a prompt asking you if youd 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
# Uncomment this for admin:
(r'^admin/', include('django.contrib.admin.urls')),
Configure Apache and mod_python
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 doesnt 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, youll 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
MaxRequestsPerChild 1
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE myproject.settings
PythonPath "['/home/YOUR_USERNAME/django_projects'] + sys.path"
SetHandler None
SetHandler None
SetHandler None
SetHandler None
Restart Apache and pray
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.
Thanks for this article. Just a quick note to let you know that I got stuck at the following step,
django-admin.py syncdb
With the following error message,
Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
But fixed it with this
python manage.py syncdb
Running from the project directory. For anyone else, run
python manage.py help
for more instructions.
use
python manage.py syncdb i think this was a typo.
Pingback: Howto Install Django on an Ubuntu Linux Server
Pingback: path for apps on debian « m3chman’s blog
I follow this instruction but when i run the command django-admin.py startproject myproject, i generate an error!!
File “/usr/local/bin/django-admin.py”, line 2, in
from django.core import management
ImportError-. No module named django.core
help me!!Tanks
I’m getting stuck on this line- it says that the directory I am using is not valid… I’m typing: (note, django is not an existing directory and I couldn’t create it)
me@me-desktop:~$ ln -s ‘pwd’ /django_src/django /usr/lib/python2.6/dist-packages/django
ln: target `/usr/lib/python2.6/dist-packages/django’ is not a directory
Hi, thanks for the guide.
Newbie Feedback:
Apparently it’s missing an instruction to create the database:
mysqladmin -u [USER] -p create django_database
The settings line has a typo “django_databae”
Not a bad idea to install phpmyadmin:
sudo apt-get install phpmyadmin
Then the syncdb command worked from the my project directory:
python manage.py syncdb
Then when I tried http://localhost, I got a nasty name ‘admin’ not defined error. To solve it, I edited urls.py and uncommented the lines at the top of the file:
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
After that I successfully got the expected 404 on http://localhost and the admin console on http://localhost/admin
Thanks for the guide. It would’ve taken a lot longer without these instructions!
Rob
I was getting the same problems and found this link:
http://www.djangobook.com/en/1.0/chapter01/
It’s recommended to install from SVN then run:
sudo python setup.py install
Nice article, unfortunately some of us are very unfortunate to be on Windows as such can’t successfully follow without hitting a few issues. One of those issues is inability to get the MySQLdb working on my Windows XP.
I have everything installed but can’t seem to get the MySQdb running despite following a few suggestions on most forums. I have Python 2.6 installed if that makes any difference.
Argh. I give up
Splendid, great tutorial!
Had to use python manage.py syncdb [Thanks Andrew Fogg], and created db in mysql.
Running Karmic Koala as a VM (Sun Virtualbox [previously innotek virtualbox]) on XP host for development testing. Done a bit of python, trying to move away from .net/aspx through django.
Thanks for this post. I am new at django and this got me straight.
Thanks for the great post. Worked perfectly (w/ AF’s tip).
Very helpful !! Thanks for putting this together, Joe.
Thanks a lot for a great article. It was very useful for me!
Nice tutorial.. crossing over from Grails to Django and I am thankful for saving me the time and headache on the setup.
setting the ENGINE in myproject/settings.py to the DB engine you want to use will clear the problem. like so
DATABASES = {
‘default’: {
‘ENGINE’: ‘mysql’,# Add’postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlit$
‘NAME’: ‘DB_name’, # Or path to database file if usin$
‘USER’: ‘usr’, # Not used with sqlite3.
‘PASSWORD’: ‘passwd’, # Not used with sqlite3.
‘HOST’: ‘localhost’, # Set to empty string for localhost$
‘PORT’: ”, # Set to empty string for default. Not used $
}
}
I put a cgi python script named: cgi_python.py
including:
________________________________
#!//usr/bin/python
#!/usr/bin/python2.5
import cgi
def main():
print “Content-type: text/htmln”
form = cgi.FieldStorage()
if form1.has_key(“id”) and form1["id"].value !=”":
print”Hello”,form1["id"].value,”"
print”______________Hints______”
else:
print”Error! Please Enter ID of RNA.”
main()
_________________________________________________
and the form1.html
includes id textbox + seq. textbox + submit botton
but the apache didn’t run the cgi_python.py so far
If you don’t want all that .svn overhead in your checkout (are you really going to be committing back to the django codebase?!?), use “svn export” instead of “svn co”
Thanks a lot for this tutorial, I tryed two days before find this incredible help. Thanks again.
I was getting an “Internal Server Error” when using your settings for the httpd.conf.
What solved it for me was (https://wiki.ubuntu.com/Django)
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
sudo vim /etc/apache2/sites-available/django-example
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/usr/share/doc/python-django-doc'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE examples.settings
Install Ubuntu-Server
sudo apt-get install libapache2-mod-python python-django python-django-doc
sudo vim /etc/apache2/sites-available/django-example
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/usr/share/doc/python-django-doc'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE examples.settings
sudo a2dissite default
sudo a2ensite django-example
sudo /etc/init.d/apache2 reload
Pingback: “Internal Server Error” when installing Django « stephen balaban
I know that ATI is the best graphics device…
After this tutorial, it gives ‘TemplateDoesNotExist at /admin/’. So that, i have to copy django-trunk/django/contrib/admin/templates/* to TEMPLATES_DIR.
Pingback: Installing Django 1.2.3 on Ubuntu 10.10 « HackRunner
If you have an issue in “Invalid command ‘PythonInterpreter’, perhaps
misspelled… bla bla bla” at the moment to restar, make next step:
sudo apt-get install libapache2-mod-python
It is because we need the library libapache2-mod-python.
That’s it!
Regards
Very nice tutorial, thank you, all works after read some comments…
Nice…. just a few comments.
On the latest release uncomment the two lines at the top of urls.py and do not comment the last line.
Now, I need to get an app going!
Sorry, I meant do not uncomment the last line…
Thank you so much for this. I was about to pull out my hair trying to get my django running. My ubuntu was missing the apache mod_python packages.
Thanks much!
Thanks for this. Minor error in the httpd.conf file line 30. should be (no space)
Looks like angle brackets not allow in comments, . On line 30 the location element has a trailing space before the angle bracket and removing the space fixes the error.
I am getting stuck at this line
“ln -s `pwd`/django_src/django YOUR-DIR/django”
when i run this line, it gives me an error of permission denied.
please help!
thanks
I’m glad i followed this instruction, installed using SVN. downloading from the official release and doing
python setup.py install
generated “ImportError-. No module named django.core” when i did start a project
but usng this approach worked fine.
Awesome steps.Thanks a lot for your kind guidance
Pingback: beginner django setup: Could not import settings ‘myproject.settings’
Pingback: Installing Django on Ubuntu -worked for me « Roshan Book