Click here to Skip to main content
Click here to Skip to main content

Teach Yourself Django in 24 Hours: Hour 2: Creating Your First Website

, 23 Apr 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Learn to implement and configure a functional database-driven website using the Django framework and MySQL.

Cover image

Title Sams Teach Yourself Django in 24 Hours
Author(s) Brad Dayley
Publisher Sams Publishing
Published Feb. 2008
ISBN 067232959X
Price USD 34.99
Pages 528

What You'll Learn in This Hour:

  • How to begin creating a Django project
  • How to start and stop the built-in web server
  • The steps to configure Django to access the database
  • How to create and install an application
  • The steps to apply a model to an application
  • The steps to activate a model in Django
  • How to configure Django to accept specific URL requests
  • How to create a simple view for a web browser

In Hour 1, "Understanding Django," you learned some of the basics about the Django framework. This hour guides you through the steps of creating a functional website called iFriends. Although this website will be basic, it will be the basis for future hours to build on as you are guided through the various aspects of the Django framework.

Creating a Django Project

Let's begin the process of creating a working website by creating a Django project. A Django project is a collection of settings that define a specific instance of Django. These settings include things such as database configuration, URL configuration, and other options that you will learn about as the hours tick by.

Try It Yourself

Create Your First Django Project

Creating a Django project is relatively simple to do from the command prompt. In this section, you create a project called iFriends.

  1. From a command prompt, change to the directory where you want to store the code for the iFriends project.
  2. Create a directory called iFriends. This will be the root directory for the iFriends project.
  3. Change to the iFriends directory.
  4. Type the following command to create the iFriends project:

    python django-admin.py startproject iFriends


Caution - Because the project will act as a Python package, avoid using a project name that conflicts with any existing built-in Python packages. The documentation for built-in Python packages can be found at http://www.python.org.



Note - There is no need to put your project code in a directory in the web server's document base. The Django framework will be responsible for executing the code. In fact, it is a much better idea to store the code somewhere outside the web server's root. That way your code will be protected from being accessed directly from a web browser.


The startproject command first creates a directory called iFriends, and then it stores the basic set of Python files that are needed to begin the project in the iFriends directory. The startproject command creates the following files:

  • __init__.py is an empty file that tells Python that the website directory should be treated as a Python package.
  • manage.py is the command-line utility that allows the administrator to start and manage the Django project.
  • settings.py is the configuration file that controls the behavior of the Django project.
  • urls.py is a Python file that defines the syntax and configures the behavior of the URLs that will be used to access the website.

The basic purpose of these files is to set up a Python package that Django can use to define the website's structure and behavior. We will discuss these files a bit more in this hour and in subsequent hours as the website gets increasingly complex.

Starting the Development Server

After you have created the Django project, you should be able to start the development server to test it. The development server is a lightweight web server that is included with the Django project. It lets you develop and test your website without having to deal with all the configuration and management issues of a production web server.

Try It Yourself

Start the Development Server

In this section, you learn how to start the development server.

  1. From a command prompt, change to the root directory for the iFriends project.
  2. Enter the following command to start the development server, as shown in Figure 2.1:
        python manage.py runserver

    Figure 2.1
    Starting the development server from a command line.


    Note - The manage.py utility is copied into the root of your project by the createproject command discussed earlier in this hour. The manage.py utility first validates the project and reports any errors. If no critical errors are encountered, you are notified that the development sever is running at http://127.0.0.1:8000/.


  3. Verify that the development server is working properly by opening a web browser and entering the following address:
        http://127.0.0.1:8000/

If the development server starts properly (and you haven't changed the debug setting), you should see a page similar to the one shown in Figure 2.2.

Figure 2.2
Initial browser view of a Django website.


Note - You can tell the development server to use a different port than 8000 if that port is already being used by adding the port to the command line. The following example shows the syntax for configuring the development server to run on port 8008:

manage.py runserver 8008


Tip - To stop the development server, press Ctrl+Break or Ctrl+C.


Configuring the Database

After you have verified that you can start and stop the development server, it is time to configure access to the database. This section takes you through the process of creating and configuring access to the database that will be used in the sample project.


Note - Django can dynamically serve web pages without using a database to store information. However, one of the best aspects of Django is its ability to implement database-backed websites.


Configuring the database involves three major steps. The first is to create the database and assign rights. The second is to modify the settings.py file to specify the database type, name, location, and access credentials. The third step is to synchronize the Django project with the database to create the initial tables necessary for the Django engine.

Django supports several different types of database engines. The project used in this book uses a MySQL database. This section assumes that you have already installed, configured, and started a database engine and that it is accessible from the development server.


Tip - The MySQL database does not allow you to use case sensitive names when creating tables. If you want to define objects in your project that have uppercase characters, then you will need to turn off case sensitivity in the Django framework by using the following setting in the <django installation path>/django/db/backends/__init__.py file:

uses_case_insensitive_names = True

Try It Yourself

Create the Database and Grant Rights

This section takes you through the steps of creating the database, creating an admin user, and granting rights from your SQL database command console. You will also modify the uses_case_insensitive_names setting in the Django framework so that you can name objects with uppercase characters. This step will be critical for some of the other Try it Yourself sections.

  1. From your SQL database command console, enter the following command to create a database called iFriends:
        CREATE DATABASE iFriendsDB;
  2. Enter the following command to begin using the iFriends database:
        USE iFriendsDB;
  3. Enter the following command to create an administrative user named dAdmin with a password called test:
        CREATE USER 'dAdmin'@'localhost' IDENTIFIED BY 'test';
  4. Enter the following command to grant all rights on the iFriends database to the dAdmin user:
        GRANT ALL ON *.* TO 'dAdmin'@'localhost';

    Note - If your database engine has a graphical interface that allows you to manage databases and users, you can use that interface as well to create the database and admin user and to assign rights.


  5. Open the <django installation path>/django/db/backends/__init__.py file in an editor.
  6. Add the following setting to the file to disable case sensitivity for the MySQL database:
        uses_case_insensitive_names = True
  7. Save the __init__.py file.

Configuring Database Access in settings.py

After the database has been created and a user account set up for Django, you need to configure the settings.py file in your Django project to access that database. Each Django project has its own settings.py file. The settings.py file is a Python script that configures various project settings.

Django uses the following settings in the settings.py file to control access to the database:

  • DATABASE_ENGINE is the type of database engine. Django accepts postgresql_psycopg2, postgresql, mysql, mysql_old, sqlite3, and ado_mssql.
  • DATABASE_NAME is the name of the database. For SQLite, you need to specify the full path.
  • DATABASE_USER is the user account to use when connecting to the database. No user is used with SQLite.
  • DATABASE_PASSWORD is the password for DATABASE_USER. No password is used with SQLite.
  • DATABASE_HOST is the host on which the database is stored. This can be left empty for localhost. No host is specified with SQLite.
  • DATABASE_PORT is the port to use when connecting to the database. This can be left empty for the default port. No port is specified with SQLite.

Try It Yourself

Configure Django to Access the iFriends Database

The following section takes you through the steps to modify the settings in the settings.py file for the database and user created in the preceding section (a MySQL database named iFriendsDB, and a username of dAdmin with a password of test running on the localhost and default port). Open the iFriends\settings.py file in a text editor.

  1. Find the DATABASE_ENGINE setting, and change the value to the following:

    DATABASE_ENGINE = 'mysql'


    Note - If you have elected to use an SQL database other than MySQL, you need to use that database type here instead of mysql.


  2. Change the value of the DATABASE_NAME setting to the following:

    DATABASE_NAME = 'iFriendsDB'

  3. Change the value of the DATABASE_USER setting to the following:

    DATABASE_USER = 'dAdmin'

  4. Change the value of the DATABASE_PASSWORD setting to the following:

    DATABASE_PASSWORD = 'test'

  5. Verify that the DATABASE_HOST and DATABASE_PORT settings have no value:
        DATABASE_HOST = ''
        DATABASE_PORT = ''

Note - When the DATABASE_HOST and DATABASE_PORT settings are left blank, they default to the localhost and default port. If the database is on a remote server or is running on a nondefault port, these options need to be set accordingly.


Synchronizing the Project to the Database

After you have configured access to the database in the settings.py file, you can synchronize your project to the database. Django's synchronization process creates the tables necessary in the database to support your project.

The tables are created based on what applications are specified in the INSTALLED_ APPS setting of the settings.py file. The following are the default settings already specified in the INSTALLED_APPS setting:

INSTALLED_APPS = (
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.sites',
)

The following list describes the default applications that get installed in the Django project:

  • django.contrib.auth is the default authentication system included with Django.
  • django.contrib.contenttypes is the framework of types of content.
  • django.contrib.sessions is the framework used to manage sessions.
  • django.contrib.sites is the framework used to manage multiple sites using a single Django installation.

Try It Yourself

Synchronize the iFriends Project to the iFriends Database

This section guides you through the steps to synchronize the Django project to the database. During the process, Django creates the default tables and prompts you to input the name, email address, and password for a website administration account. The username and password you specify allow you to access the Django authentication system.

  1. Make certain that the development server has stopped by pressing Ctrl+Break from the console prompt.
  2. Change to the root directory of the iFriends project.
  3. Enter the following command at the console prompt to begin the synchronization, as shown in Figure 2.3:

    python manage.py syncdb

    Figure 2.3
    Synchronizing the initial Django project with the database from a command line.

  4. At the prompt, enter a username for the website administrator's account.
  5. At the prompt, enter a password for the website administrator's account.

The database now has the appropriate tables configured to allow Django to use its authentication, content, session, and site frameworks correctly.

Installing an Application

After you have configured and synchronized the database, you can begin installing applications in it. Installing applications is simply a matter of creating an application directory, defining a model, and then activating the application so that Django can access it in the database.

Try It Yourself

Create Your First Application

The first application you will create is an application called People, which will be used to keep track of the individuals who use the website.

  1. From a console prompt, change to the root directory of the iFriends project.
  2. Enter the following command to create a blank application called People:
        python manage.py startapp People

The startapp command creates a People directory within the iFriends directory and then populates it with the following files:

  • __init__.py is a necessary file for the application to be used as a Python package.
  • models.py contains the Python code that defines the model.
  • views.py contains the Python code that defines the views for the model.

The files in the application directory define how information for the application will be stored and accessed in the database. They also define how information in the model will be viewed when accessed from the website.

Creating a Model

After the application has been created, you need to create a model for the data that will be stored in the application. A model is simply a definition of the classes, attributes, and relationships of objects in the application.

To create a model, you need to modify the models.py file located in the application directory. The models.py file is a Python script that is used to define the tables that will be added to the database to store objects in the model.

The models.py file initially has only one line, which imports the models object from the django.db package. To define the model, you need to define one or more classes. Each class represents an object type in the database.

Try It Yourself

Create a Model for the People Application

In this section, you create the class Person in the People model by modifying the Python script, models.py, for the People application. Initially, the script is blank. This section takes you through adding the Python code to define classes in the model.

  1. Open the iFriends\People\models.py file in an editor.
  2. Add the following line of code to the file to import the Django models package into the application:

    from django.db import models

  3. Add the following code snippet to define the Person class with name, email, headshot, and text attributes:
        class Person(models.Model):
          name = models.CharField('name', maxlength=200)
          email = models.EmailField('Email', blank=True)
          headshot = models.ImageField(upload_to='img', blank=True)
          text = models.TextField('Desc', maxlength=500, blank=True)
          def __str__(self):
            return '%s' % (self.name)
  4. Save the file.

Listing 2.1 shows the complete code for the iFriends\People\models.py file.

Listing 2.1 Full Contents of the iFriends\People\models.py File

from django.db import models

class Person(models.Model):
  name = models.CharField('name', max_length=200)
  text = models.TextField('Desc', max_length=500, blank=True)

  def __str__(self):
    return '%s' % (self.name)

Note - The definition for __str__ defines a string representation of the object that can be used in views or other Python scripts. Django uses the __str__ method in several places to display objects as well.


Try It Yourself

Activate the Person Model

This section takes you through the process of activating the Person model by adding it to the INSTALLED_APPS setting in the settings.py file and then synchronizing the database.

  1. Open the iFriends\settings.py file in an editor.
  2. Find the INSTALLED_APPS setting, and add the iFriends.People application to it, as shown in the following snippet:
    INSTALLED_APPS = (
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.sites',
      'iFriends.People',
)
  1. Save the file.
  2. Synchronize the People application into the iFriends database by using the following command from the root of the iFriends project, as shown in Figure 2.4:
        python manage.py syncdb

Figure 2.4
Synchronizing the new People application with the database from a command line.

The syncdb command creates the necessary tables in the iFriends database for the People application. The model is now active, and data can be added to and retrieved from the database using Django at this point.

Adding Data Using the API

This section briefly describes how to use the Django shell interface and database API to quickly add a single Person object to the People table. The Django shell is a Python shell that gives you access to the database API included with Django. The database API is a set of Python methods that allow you to access the project database from the data model.

Try It Yourself

Add a Person Object to the iFriends Database

Open the Django shell, and follow these steps to add yourself as a Person object in the People model of the iFriends database.

  1. From a console prompt, change to the root directory of the iFriends project.
  2. Enter the following command to invoke the Django shell:

    python manage.py shell

  3. From the shell prompt, enter the following to import the Person class from the People package:

    from iFriends.People.models import Person

  4. Enter the following command to create a Person object named p:

    p = Person(name="<your name>", email="<your eMail>")

  5. Save the Person object you just created using the following command:

    p.save()

  6. Verify that the object was created by using the Person.objects.all() function, which returns a list of all Person objects, and then print the list:
        lst = Person.objects.all()
        print lst

    Figure 2.5 shows these commands.

Figure 2.5
Using the Python shell to add an object to the database.

A Person object has now been created in the iFriends database. We will discuss accessing the database and using the database API in more depth later.

Setting Up the URLConf File

This section discusses configuring the URLConf file to define how installed applications are accessed from the web. The URLConf file is a Python script that allows you to define specific views that are accessed based on the URL that is sent by the web browser. When the Django server receives an URL request, it parses the request based on the patterns that are contained in the URLConf file. The parsed request is translated into a specific Python function that is executed in the views.py file, discussed in a moment.


Note - The location of the URLConf file is defined by the ROOT_URLCONF setting in the settings.py file. The default location is the name of the project's root directory. In the case of the iFriends project, the value of ROOT_URLCONF would be set to the following value, where 'iFriends.urls' equates to iFriends/urls.py:

ROOT_URLCONF = 'iFriends.urls'

Try It Yourself

Add an URL Pattern to Use for a People View

In this example, you set up a simple URL pattern for the People application by modifying the urlpatterns setting in the iFriends/urls.py file.

  1. Open the iFriends\urls.py file in an editor.
  2. Find the urlpatterns setting, and add the iFriends.People.views.index pattern to it:
        urlpatterns = patterns('',
          (r'^People/$', 'iFriends.People.views.index')
        )
  3. Save the file.

Note - In the preceding code snippet, iFriends.People.views.index refers to the index() function located in the iFriends/People/views.py file, which is discussed next.


Creating a Simple View

After you have configured the URLConf file, you need to add the views to the application. The application's views are stored as functions in the views.py file in the application directory. When the Django server receives an URL request, it parses the request based on the patterns that are contained in the URLConf file and determines which function to execute to generate the web view.

Try It Yourself

Create the Index View for the People Application

This section guides you through the steps of creating an index view stub for the People application in the iFriends project. After the view is created, you start the development server and view the web page that is generated.

  1. Open the iFriends/People/views.py file in an editor. The views.py file is empty at first.
  2. Use the editor to add the following code snippet to the file:
        from django.shortcuts import HttpResponse
        from iFriends.People.models import Person
        
        def index(request):
          html = "<H1>People</H1><HR>"
          return HttpResponse(html)
  3. Save the file.
  4. From a command prompt, change to the root directory for the iFriends project.
  5. Enter the following command to start the development server:

    python manage.py runserver

  6. Access the http://127.0.0.1:8000/People URL. You should see a web page similar to the one shown in Figure 2.6.

Figure 2.6
Accessing a custom index view in the Django project from a web browser.

Summary

In this hour, you created a Django project called iFriends. You configured access to a MySQL database for the project. You created an application called People, added a Person class, and populated the database with one Person object. You then configured the URL behavior to support an index view and added the necessary code in that view to display a list of objects in the Person class.

The steps you took during this hour helped demonstrate how easy it is to set up a website using the Django framework. Subsequent hours will build on this framework to implement a full-featured website.

Q&A

  1. How do I modify a model after it has been synced to the database?
  1. Currently, Django cannot update models reliably. The safest and easiest method to modify an existing model is to make changes to the model and then delete all tables related to the model in the database using the SQL drop command. Finally, use the syncdb command to sync the model with the database.
  1. Is there a way to check for errors in my model before trying to sync to the database?
  1. Django has a utility to validate the contents of models before syncing to the database. From the root directory of the project, enter python manage.py validate. The validate utility checks the model's syntax and logic and reports any problems.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

  1. What file contains the information that Django uses to connect to the database?
  2. What default file contains the configuration that Django uses to parse the location URLs?
  3. What file contains the code that implements an index view for the People application in the iFriends project?

Quiz Answers

  1. settings.py
  2. urls.py
  3. iFriends/People/views.py

Exercises

Try your hand at creating and activating a simple application. Create an application called Comments. Add a class to the model called Note, with two CharField attributes called Title and Text. Then activate the model by adding it to the INSTALLED_APPS setting in the settings.py file. Synchronize the model to the database. Test your application by adding an object to the database using the Django shell.


This sample content is an excerpt from the book, Sams Teach Yourself Django in 24 Hours, by Brad Dayley, published February 2008, ISBN 067232959X Copyright 2008 by Sams Publishing. For more information: www.informit.com/title/067232959X.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sams Publishing

United States United States
No Biography provided
Group type: Organisation

1 members


Comments and Discussions

 
Generalgood article for beginners Pinmembersomnathzankar17-Sep-12 20:47 
Generalthis should be going under python category Pinmembermascix23-Apr-08 21:37 
GeneralRe: this should be going under python category Pinmemberblackjack215023-Apr-08 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 23 Apr 2008
Article Copyright 2008 by Sams Publishing
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid