Applications

Within Django project, we can have multiple apps that have different functions.

For example, we can have a Blog section and a Store section for our site.

It will be useful to seperate different parts of our project.

If we prefer a certain app, we can also add it to other projects.

Create an application

To create an application, we run python manage.py startapp APP_NAME. This will create some additional directories and files.

For example, in mysite directory, we run python manage.py startapp blog.

We can view the directory structure with 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-38.pyc
    │   ├── settings.cpython-38.pyc
    │   ├── urls.cpython-38.pyc
    │   └── wsgi.cpython-38.pyc
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Install new app

To install new app, we go to settings.py, scroll down to the list of INSTALLED_APPS, and add the name of our new application to this list.

# Application definition

INSTALLED_APPS = [
    'blog.app.BlogConfig', # Add blog app
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Create a view

First, we open view.py

To create our first view, we’ll write a function that takes in a request.

In this example, we’ll simply return an HttpResponse (A very simple response that includes a response code of 200 and a string of text that can be displayed in a web browser) of “My blog”.

To do this, we have include from django.http import HttpResponse.

Our file now looks like:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('<h1>My blog</h1>')

To associate the view we have just created with a specific URL, we create another file called urls.py in the same directory as views.py

We already have a urls.py file for the whole project, but we should have a separate one for each individual app.

Step 1

In our new urls.py, we’ll create a list of url patterns that a user might visit while using our website.

  1. We have to import:
  • from django.urls import path (reroute URLs)
  • from . import views (import any functions we’ve created in views.py.)
  1. Create a list called urlpatterns

  2. For each URL, add an item to the urlpatterns list that contains a call to the path function with two or three arguments:

  • A string representing the URL path
  • a function from views.py to call when that URL is visited
  • a name for that path (optionally) in the format name="something".

For example

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index")
]

Step 2

After creating a urls.py for this specific application, now we edit the urls.py for the entire project.

This URL will tell our whole website which URL will send us to our app.

  1. Open urls.py in mysite directory.
  2. Import include function from django.urls
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 blank.

For example: path('', include("blog.urls"))

Step 3

If we’d like to add another page in Blog app

  1. Add function in views.py
  2. Add path in app’s urls.py

For example, if we’d like to create an About page in blog.

  1. Open views.py and add
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('<h1>My blog</h1>')

def about(request):
    return HttpResponse('<h1>About</h1>')
  1. Open blog’s urls.py and add
from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("about/", views.about, name="blog-about")
]

Optional

If we have different users, we can implement individual URL path for each user.

For example, in views.py we have function greet

def greet(request, name):
    return HttpResponse(f"Hello, {name.capitalize()}!")

In urlpatterns of urls.py, we add:

path("<str:name>", views.greet, name="greet")

We’re no longer looking for a specific word or name in the URL, but any string that a user might enter.

For instance, if user type localhost:8000/blog/hanna, it will return Hello, Hanna

Summary

Here is a brief summary on how to create a new app named blog

  1. run python manage.py startapp blog in the terminal.

  2. Edit settings.py, add “blog” as one of our INSTALLED_APPS

INSTALLED_APPS = [
    'blog.apps.BlogConfig'
]
  1. Edit our project’s urls.py file, and include a path path('blog/', include("blog.urls"))

  2. Create another urls.py file within our new app’s directory, and update it

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
]
  1. Create an index function in views.py
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "blog/index.html")

Note: In this example, we render our index function with Django template.