Creating your first project

Our first Django project will be building a complete blog. Django provides a command that allows you to create an initial project file structure. Run the following command from your shell:

django-admin startproject mysite

This will create a Django project with the name mysite.

Avoid naming projects after built-in Python or Django modules in order to avoid conflicts.

Let's take a look at the project structure generated:

mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py

These files are as follows:

  • manage.py: This is a command-line utility used to interact with your project. It is a thin wrapper around the django-admin.py tool. You don't need to edit this file.
  • mysite/: This is your project directory, which consists of the following files:
    • __init__.py: An empty file that tells Python to treat the mysite directory as a Python module.
    • settings.py: This indicates settings and configuration for your project and contains initial default settings.
    • urls.py: This is the place where your URL patterns live. Each URL defined here is mapped to a view.
    • wsgi.py: This is the configuration to run your project as a Web Server Gateway Interface (WSGI) application.

The generated settings.py file contains the project settings, including a basic configuration to use an SQLite 3 database and a list named INSTALLED_APPS, which contains common Django applications that are added to your project by default. We will go through these applications later in the Project settings section.

To complete the project setup, we will need to create the tables in the database required by the applications listed in INSTALLED_APPS. Open the shell and run the following commands:

cd mysite
python manage.py migrate

You will note an output that ends with the following lines:

Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK

The preceding lines are the database migrations that are applied by Django. By applying migrations, the tables for the initial applications are created in the database. You will learn about the migrate management command in the Creating and applying migrations section of this chapter.