How to Create a New App in Django

One of the main principles behind a Django project is to have each significant "component" contained within its own app. This makes it easy to add and remove reusable apps within different projects.

 

In this tutorial, we will learn how to create a new app in a Django project from the command line.

 

Step 1

Open your terminal and go to the root of your project where your manage.py file is located using the cd command.

 

cd myproject

 

Now run the following command, replacing appName with the name of the app you'd like to create inside your project:

 

python manage.py startapp appName

 

Step 2

Open the settings.py file in the root of your project and locate the INSTALLED_APPS array and add your new app like this:

 

myproject/settings.py
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',

   # packages
   "compressor",

   # own
   'appName' # your app.
]

 

It's good practice to separate the built-in Django, third-party and your own apps using comments.

 

Step 3

The final step is to include the URLs from the new app so that Django knows to try them when a request is made.

 

Open the urls.py file in the root of your project. Then, if it isn't already there, import the include and path class from django.urls at the top of the file like this:

 

myproject/urls.py
from django.urls import include, path

 

Now inside the urlpatterns array include the urls.py file from your new app like this:

 

urlpatterns = [
  path('', include('appName.urls'))
]

 

That's it! You can now work from within your app to capture requests.

django