Django Modularisation

Yashod Perera
Nov 3, 2020
Photo by Jan Huber on Unsplash

Why not to develop all in the main module. Ohhhh? That will be cumbersome when you go for larger scale applications or projects. Modularisation will be easier in django.

First Let’s make the project named django_modules and make and a module django_app (these modules are called as apps in django). Make sure that you have installed django in your machine.

django-admin startproject django_modules
cd django_modules
django-admin startapp django_app

Then you will get following project structure.

Let’s register the application in django_modules/settings.py as follows.

# Application definitionINSTALLED_APPS = [
...
'django_app',
]

Then you can make django_app/urls.py on the module to isolate its urls and views.

First let’s make a small view in django_app/views.py .

from django.http import HttpResponsedef test_view(request):
if request.method == 'GET':
return HttpResponse(content="Hi", status=404)

Then add this view to a url in django_app/urls.py .

from django.urls import path
from .views import test_view
urlpatterns = [
path('test/', test_view),
]

The final step is to add your modules url file to the project url file as follows. I have added in django_modules/urls.py .

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('django_app.urls'))
]

Then run the application using python manage.py runserver and when you go to the http://127.0.0.1:8000/app/test it will show “Hi” message.

If you get error running python manage.py runserver use python3 manage.py runserver .

By modularising you can break your application in to several modules which will help you to understand the code easily and maintain the code easier.

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor