Within a Django project, we can have multiple apps with different functions.
For example, our site can have a Blog section and a Store section. There is a different app for each task.
In this tutorial, we’ll learn.
There are several benefits of creating an app.
Django provides some pre-installed apps for users. To check them, we can navigate to projectName –> settings.py.
In the settings.py file, you will find INSTALLED_APPS.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
To create an application, we run python manage.py startapp APP_NAME
. This will create some additional directories and files.
For example, in the mysite
directory, we run python manage.py startapp blog
.
We can view the directory structure with the tree
command:
.
├── blog
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
└── mysite
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-39.pyc
│ ├── settings.cpython-39.pyc
│ ├── urls.cpython-39.pyc
│ └── wsgi.cpython-39.pyc
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
To install our new app in this project, go to projectName -> settings.py, and scroll down to the list of INSTALLED_APPS
.
We then add the name of our new application to this list.
INSTALLED_APPS = [
'blog.apps.BlogConfig', # Add blog app
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
We’ll then need to render an app. This URL will tell which URL will send us to our app.
include
function from django.urls
in the header.from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include("blog.urls"))
]
Note: If you’d like your Blog page to be your front page, you can leave it blank.
For example: path('', include("blog.urls"))
.
Here is a brief summary of how to create a new app named blog
Run python manage.py startapp blog
in the terminal to create a new app.
To add our app to the project, edit project’s settings.py, and add “blog” as one of our INSTALLED_APPS.
INSTALLED_APPS = [
'blog.apps.BlogConfig'
]
path('blog/', include("blog.urls"))
Next, check out Django views.