Starting a Django Application

Starting a Django Application

After we have created a Django Skeleton Project, we can go ahead to create an application for our project.

In the project folder containing manage.py file, we would enter python manage.py startapp <app name> on the terminal. If we want our Django application to be named blog, we would enter;

python manage.py startapp blog
cd blog

We would have a file tree structure of this nature;

C:.
└───mysite
    │   db.sqlite3
    │   manage.py
    │
    ├───blog
    │   │   admin.py
    │   │   apps.py
    │   │   models.py
    │   │   tests.py
    │   │   views.py
    │   │   __init__.py
    │   │
    │   └───migrations
    │           __init__.py
    │
    └───mysite
        │   asgi.py
        │   settings.py
        │   urls.py
        │   wsgi.py
        │   __init__.py
        │
        └───__pycache__
                settings.cpython-310.pyc
                urls.cpython-310.pyc
                wsgi.cpython-310.pyc
                __init__.cpython-310.pyc

Adding Application to Settings.py

We would need to add our application to our settings.py file. In our apps.py in our application folder, we would find;

from django.apps import AppConfig


class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'

We need to add BlogConfig to our ÌNSTALLED_APPS in our settings.py file; we would do that by entering the following in our settings.py file.

...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog.apps.BlogConfig' # Application added
]
...

Adding Our Application's URLs to the Project's urls.py File

First, we would create a urls.py file in our application's folder. Next, we would include our blog URLs in our project's urls.py file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')), # blog urls
]

To access our blog (based on the code above), we would have to visit 127.0.0.1:8000/blog. If we change the path of our blog.urls from 'blog/' to '' , our blog would be found at http://127.0.0.1:8000.

Creating a View and Its URL Path

In our views.py in our application folder, we would create a simple view.

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

def home(request):
    return HttpResponse('Bienvenue')

For us to access the view in our browser, we would have to attach the view to a URL path in our urls.py file in our application folder.

from django.urls import path, include
from blog import views

urlpatterns = [
    path('', views.home, name='home')
]

When we visit 127.0.0.1:8000/blog on our browser (after python manage.py runserver on the terminal), we would see;

A web page.

This tutorial is just the basic of what is possible.