How To Create / Remove Django Project Application

Each Django project can have multiple applications. Each application can have multiple models and each model has mapped to one table in the backend database. This article will tell you how to create Django project application. How to remove all database table of the application and how to remove the application completely.

1. Install Django.

First use pip3 show django command to see whether Django has been installed or not. If not then use pip3 install django==2.1 command to install Django to your local computer. You can specify the Django version number after ==.

$ pip3 install django==2.1

2. Create Django Project.

When you install Django successfully, run pip3 show django to get Django installation directory data. You can see that Django has been installed in directory like /Users/zhaosong/anaconda3/lib/python3.6/site-packages

192:~ zhaosong$ pip3 show django
Name: Django
Version: 2.1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: /Users/zhaosong/anaconda3/lib/python3.6/site-packages
Requires: pytz

Now run env command in terminal to get the PATH value, we can see that directory like /Users/zhaosong/anaconda3/bin is just in the PATH value. So when you run a command in terminal, OS will find the command in /Users/zhaosong/anaconda3/bin directory first.

192:~ zhaosong$ env
PATH=/Users/zhaosong/anaconda3/bin:......

Now cd into the PATH folder /Users/zhaosong/anaconda3/bin, then we can find two Django admin related executable file in it.

192:bin zhaosong$ pwd

/Users/zhaosong/anaconda3/bin

192:bin zhaosong$ ls -l django-admin*

-rwxr-xr-x  1 zhaosong  staff  287 Aug 30 23:14 django-admin

-rwxr-xr-x  1 zhaosong  staff  145 Aug 30 23:14 django-admin.py

Now you can create Django project by execute above command with startproject command argument like below.

$ django-admin.py startproject DjangoHelloWorld

Above command will create a project folder DjangoHelloWorld in current directory, it contains the basic files and directory structure of the Django project like below.

DjangoHelloWorld
       |
       |-----DjangoHelloWorld
       |----------|-----------__init__.py
       |----------|-----------settings.py
       |----------|-----------urls.py
       |----------|-----------wsgi.py
       |-----manage.py
  1. settings.py : This file is very important, it record the project level information such as installed applications, backend database etc. The Django project default database is sqlite3, it is configured in settings.py file like below. You can use other database such as MySQL to replace it, please refer article How To Connect MySQL Database In Django Project
    .DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
  2. urls.py : This file is also important, it maps request url to related installed Django project application to process.

3. Create Django Application.

After you create Django project, you can create and add multiple applications in it.

  1. CD into Django project root folder.
  2. Run $ python3 manage.py startapp app1 command to create application app1.
  3. Now you can find the folder app1 in DjangoHelloWorld directory. And there are below skeleton files in app1 directory.
    /Users/zhaosong/DjangoHelloWorld/app1
    192:app1 zhaosong$ ls -l
    total 40
    -rw-r--r--  1 zhaosong  staff   0 Feb  6 20:57 __init__.py
    -rw-r--r--  1 zhaosong  staff  63 Feb  6 20:57 admin.py
    -rw-r--r--  1 zhaosong  staff  83 Feb  6 20:57 apps.py
    drwxr-xr-x  3 zhaosong  staff  96 Feb  6 20:57 migrations
    -rw-r--r--  1 zhaosong  staff  57 Feb  6 20:57 models.py
    -rw-r--r--  1 zhaosong  staff  60 Feb  6 20:57 tests.py
    -rw-r--r--  1 zhaosong  staff  63 Feb  6 20:57 views.py
  4. Now you should add app1 in Django project settings.py file INSTALLED_APPS section to make it managed by the project.
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app1',
    ]

4. Create Django App Models Mapped Database Table.

Each Django app can have multiple models, each model has a related table in the backend database. You can define model in app1/models.py file.

But for a newly created Django project, you need to run python3 manage.py migrate command first to initialize the Django project built-in module ( such as auth, session, admin, contenttypes), this command will create above built-in module used backend database table in the database.

The python3 manage.py makemigrations command is used to detect whether there are any model changes in the history, since this is the Django project first time initialization, there are no changes.

192:DjangoHelloWorld zhaosong$ python3 manage.py makemigrations
No changes detected
192:DjangoHelloWorld zhaosong$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... 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

Now the Django project built-in admin site has been created, you can start the Django server with command python3 manage.py runserver.

192:DjangoHelloWorld zhaosong$ python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
February 06, 2019 - 13:21:42
Django version 2.1, using settings 'DjangoHelloWorld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Now browse the server url at http://127.0.0.1:8000/, and the server admin website url is http://127.0.0.1:8000/admin. But now you may be confused because of you do not know  what username and password to input. So you need to create a super user use command python3 manage.py createsuperuser

192:DjangoHelloWorld zhaosong$ python3 manage.py createsuperuser
Username (leave blank to use 'zhaosong'): admin
Email address: admin@dev2qa.com
Password: 
Password (again): 
Superuser created successfully.

Use the superuser account to login to the Django project admin website again. Now you can refer article How To Manage Models In Django Admin Site to add models in app1.

After you add model definition in app1/models.py file, you can run $ python3 manage.py makemigrations app1 command in terminal to detect the model changes for app1.

192:DjangoHelloWorld zhaosong$ python3 manage.py makemigrations app1
Migrations for 'app1':
  app1/migrations/0001_initial.py
    - Create model Department_User
    - Create model Employee_User
    - Alter unique_together for department_user (1 constraint(s))
    - Alter unique_together for employee_user (1 constraint(s))

If you confirm the changes, run $ python3 manage.py migrate app1 to apply the model changes to the backend database. All the migration process is saved in app1 / migrations folder. There are several .py file, open that file in text editor, you can find the operations in it like below.

# Generated by Django 2.1 on 2019-02-06 13:41

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Department',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('dept_name', models.CharField(max_length=1000)),
                ('dept_desc', models.CharField(max_length=1000)),
            ],
        ),
        migrations.CreateModel(
            name='Employee',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('emp_mobile', models.CharField(max_length=100)),
                ('emp_salary', models.IntegerField()),
                ('emp_onboard_date', models.DateTimeField(auto_now=True)),
                ('dept', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app1.Department')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='department',
            unique_together={('dept_name',)},
        ),
        migrations.AlterUniqueTogether(
            name='employee',
            unique_together={('emp_mobile',)},
        ),
    ]

If you meet any error in the migration process, you can delete all the .py file and __pycache__ folder in app1/migrations folder and migrate again, this can fix the migration error in general, but for data safe, you can backup the migrations folder to somewhere for later use.

5. Remove Django App Database Table.

There are two methods to remove Django application database tables.

5.1 Remove tables use dbshell.

  1. Run $ ./manage.py dbshell command in a terminal.
    zhaotekiMacBook-Pro:DjangoHelloWorld zhaosong$ ./manage.py dbshell
    SQLite version 3.23.1 2018-04-10 17:39:29
    Enter ".help" for usage hints.
    sqlite>
  2. Then execute .databases command to show current database file.
    sqlite> .databases
    main: /Users/zhaosong/DjangoHelloWorld/db.sqlite3
  3. Run .tables to show all tables in current database.
    sqlite> .tables
    auth_group                  auth_user_user_permissions
    auth_group_permissions      django_admin_log          
    auth_permission             django_content_type       
    auth_user                   django_migrations         
    auth_user_groups            django_session
  4. Remove related table use drop table table_name command.
    sqlite> drop table app1_department;
  5. If you want to learn more dbshell command, please type .help to show the command list.

5.2 Remove tables use SQLiteStudio.

If you use sqlite3 as the default database, then you can use SQLiteStudio to remove tables. Please refer article How To Install SQLite3 On Mac. If you use MySQL as the database server, then use your favorite MySQL manager tool to remove MySQL tables.

5.3 Remove Django application from project.

After remove django app model tables, you can remove django app follow below steps.

  1. Comment or remove ‘app1’ from Django project settings.py file INSTALLED_APPS section.
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        #'app1',
    ]
  2. Run ./manage.py makemigrations  and ./manage.py migrate app1 command to remove app1. This command will remove app1 related database tables also.
  3. Delete app1 folder.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.