Create A Django Project

The previous article Introduction to Python’s Django presented an overview of the Django Framework. In this article, we are going to write a simple Django application from scratch. The first step is to create a project using one of Django’s built-in commands django-admin.py. In a Virtualenv, type this command:

django-admin.py startproject myblog

django-admin.py is a convenient shell executable that provides a list of subcommands to manage a Django application. In the previous example, the subcommand startproject creates a Django project directory structure in the current directory:

myblog/
  manage.py
  myblog/
    __init__.py
    settings.py
    urls.py
    wsgi.py
  • myblog is the parent directory of your Django project myblog. It can be renamed to anything you like since it’s just a container.
  • manage.py is a command-line utility that lets you interact with the Django project myblog in various ways. This utility is very helpful for debugging or exercising the code.
  • myblog/myblog is the directory that contains the actual Python package for your project. Since it’s a normal Python package, you can import any module or package inside it using normal Python syntax. For example, import myblog.settings import the settings module within the package myblog.
  • myblog/myblog/settings.py is the settings or configuration for your Django project. It contains a list of global configurations which are used throughout the whole project.
  • myblog/myblog/urls.py declares URL routes for this project. It contains a list of URL mappings that tell the project how a HTTP(S) request is handled by which view function.
  • myblog/myblog/wsgi.py is an script for running your Django project in WSGI-compatible webservers.

Since we have a Django project, let’s run it!

python manage.py runserver
Validating models...
 
0 errors found
March 20, 2013 - 21:15:27
Django version 1.5, using settings 'myblog.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Accessing http://127.0.0.1:8000/ in your favorite browser will show a welcome page. The default IP address of a Django application is 127.0.0.1 which can be accessed only from your local machine. If you want to show your application to other computers, you can modify the ip address and port like python manage.py runserver 0.0.0.0:8000 which allows your Django application to listen on all public IPs.

Setup a Database in Django

One of the most important aspects of any significant website is a database backend. Since the database backend is usually configured as a global environment variable, Django provides a convenient configuration default item in myblog/settings.py to handle all kinds of database configurations.

Django and MySQL

In the Virtualenv that contains your Django application, run the following command:

pip install mysql-python

This will install the MySQL Python driver. This driver will be used by Django’s Object Relational Mapping (ORM) backend to communicate with the MySQL server in raw SQL statements.

Then, execute the following statements in a mysql shell to create a user and a database for your Django application.

mysql> CREATE USER 'pythoncentral'@'localhost' IDENTIFIED BY '12345';
mysql> CREATE DATABASE myblog;
mysql> GRANT ALL ON myblog.* TO 'pythoncentral'@'localhost';

Now, modify myblog/settings.py.

DATABASES = {
    'default': {
        # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'
        'ENGINE': 'django.db.backends.mysql',
        # Or the path to the database file if using sqlite3
        'NAME': 'myblog',
        # The following settings are not used with sqlite3
        'USER': 'pythoncentral',
        'PASSWORD': '12345',
        # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP
        'HOST': '',
        # Set to empty string for default
        'PORT': '',
    }
}

Then, run the following command to initialize the database for your Django application.

python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
 
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'myusername'):
Email address:
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Finally, a brand-new MySQL database backend has been created! You can interact with the new database by

python manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: myusername>]

Django and PostgreSQL

Like MySQL, we install a Python PostgreSQL driver in the virtualenv.

pip install psycopg2

Then, execute the following statements in a PostgreSQL shell to create a user and a database for your Django project.

postgres=# CREATE USER pythoncentral WITH PASSWORD '12345';
CREATE ROLE
postgres=# CREATE DATABASE myblog;
CREATE DATABASE
postgres=# GRANT ALL PRIVILEGES ON DATABASE myblog TO pythoncentral;
GRANT

Now, modify myblog/settings.py.

DATABASES = {
    'default': {
        # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        # Or path to database file if using sqlite3
        'NAME': 'myblog',
        # The following settings are not used with sqlite3
        'USER': 'pythoncentral',
        'PASSWORD': '12345',
        # localhost is necessary for PostgreSQL 9.2
        'HOST': 'localhost',
        # Set to empty string for default
        'PORT': '',
    }
}

Then, run the following command to initialize the database backend for your Django application.

python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
 
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'myusername'):
Email address:
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Finally, you can interact with the new Django application using the built-in shell.

python manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: myusername>]

Notice that Django’s shell is agnostic towards the database backend when you are querying all the User objects. The same code User.objects.all() works for both MySQL and PostgreSQL to retrieve a list of all users in the database.

Introduction to Django Summary

In this article, we created our first Django application myblog and tested it against a MySQL backend as well as a PostgreSQL backend. Using Django’s ORM, we can write database CRUD (Create, Read, Update, Delete) operations without caring about the underlying database backend. In the following articles of the series, we’re going to use Django’s ORM extensively for almost all database code.

Leave a Reply

Your email address will not be published. Required fields are marked *