Django Apps: A Brief Introduction

Before diving straight into Django Apps, let’s discuss what actually a Django project is? A Django project is basically the module where all the functionality, settings, and configurations of your website lie. It consists of some settings files, a manage.py file to interact with the project, and some apps for different functionalities. Instead of creating multiple apps, you can create one app and throw all your code in that one app but that will kill the purpose of Django Framework.

A project’s root directory that contains the manage.py file is the home to all the apps in that project.

 

Django Apps

 

Django app is basically a submodule of your Django project which contains code related to one functionality. Apps include models required for the functionality to interact with the database. They have views implemented for the functionality and they may also contain templates to be used in the views. 

The fact that how you break your whole website context into different apps depends upon how independent your different functionalities in the context can persist. For example in your requirements you want multiple authentications like JWT and social auth, you will create a separate app for authentication where you will implement your authentication functionality.

In that app, you will write your authentication models, views, and templates.

Another example is that you are developing an e-commerce application and you want to implement the cart functionality. You want a user to add products in his cart and then the whole checkout flow. In that case, you can have a separate app for cart only and in that app, you can implement the functionalities of adding products and then checking a user out. 

 

Benefits of using Apps in Django

Easy Debugging

The implementation of Apps in Django is such an amazing feature that it has reduced the amount of time to understand what’s happening in the code and then debug the issues. Suppose you are having issues with the authentication system. In that case, you can just go to your authentication app and look into all the models and views for authentication and easily find your issue.

Code Reusability

Django apps allow us to copy the whole app and paste it into another project with very little to no coding required. You just have to register the app in INSTALLED_APPS and you are good to go. For example, if you are creating two different eCommerce platforms and both have the cart functionality then you can just copy the cart app from one project and paste it into the other one make some tweaks according to the requirements of the project and you will see a fully functional cart functionality in that project too.

Clean code

Apps in Django are designed for easy, clean, and readable coding. The process of having multiple submodules in your project for each individual functionality lets you write good code in a very short amount of time. With one simple command, you will have a python submodule with all necessary views, models, and configuration files set up. With the proper naming convention of your app, you can make your project highly readable and understandable.

 

Easy to maintain

When you are following a proper convention of naming your application, it makes your code easy to maintain. For example, if you want to add new functionality or update the existing one in the cart, you can just go to the cart app and make your changes.

 

Looking to Hire Python/Django Development Team?

Share the details of your request and we will provide you with a full-cycle Python/Django development team under one roof.

Get an Estimate

 

Writing a Django App

You can start writing your first Django App by running the command in your project root folder

>>> python manage.py startapp <your-app-name>

After the command is finished running, you will see a python module created in your project folder. In that module, you will see multiple python files already created for you like models.py, views.py, apps.py, etc. 

After the app is created you need to register it with Django’s AppRegistry. In order to do so, you have to add it to the INSTALLED_APPS list in your project’s settings file.

INSTALLED_APPS = [
 ...
 'your-app-name'
]

 

If you are using your own custom AppConfig class, then you have to explicitly set default=True in that config class for Django to take it as default AppConfig. If you have multiple AppConfig classes, then you can set the path of one AppConfig class that you want to use to configure the app. For example, your app name is polls, and you want to configure PollAppConfig class in your app’s apps.py file then you will do something like this

 

INSTALLED_APPS = [
 ...
 'polls.apps.PollsAppConfig'
]

If you are writing an app that can be used in multiple projects then you can create your AppConfig class like this:
If your app name is authentication:

# authentication/apps.py

from django.apps import AppConfig

class AuthenticationAppConfig(AppConfig):
        name = 'authentication'
        verbose_name = 'Authentication'

 

Now you just need to copy your app to any project and add ‘authentication’ in the INSTALLED_APPS of that project.

If your app has two different AppConfigs with a different configuration, you have to either set default=True to anyone of that config for Django to take it as a default configuration file, then when the user adds ‘authentication’ in INSTALLED_APP then that configuration will be loaded. To load the other configuration, you have to explicitly do something like this:

INSTALLED_APPS = [
 ...
 'authentication.apps.CustomAppConfig'
]

 

AppConfig Attributes

  • name: this attribute tells Django which Apps this configuration applies to
  • verbose_name: this is the human-readable name of the application
  • default: this tells Django to pick this config as default or not
  • label: this is the short form of the name attribute. It is used to distinct apps with the same name
  • default_auto_field: this tells Django the type of primary key field to be used for this app’s models. The default value is AutoField, you can change that to another field.

Read-only attributes

  • module: Root module for the application. For example <module mysite.authentication from ‘mysite/authentication’>
  • Models_module: Module containing the models. For example <module mysite.authentication.models from ‘mysite/authentication/models’>

AppConfig Methods

  • get_models(): this method returns an iterable of Model classes of that app. This requires the app registry to fully populate
  • get_model(model_name, require_ready=True): this method returns Model with the given model_name attribute. It requires the app registry to be fully populated unless require_ready is set to False. This method raises LookupError when no Model with that name is found.
  • ready(): It is called as soon as the app registry is fully populated. You can override this method to make initialization tasks such as registering the signals etc. You can not import models directly where AppConfig class is defined. Instead, you have to do it in this method.

For registering the signals, you have to refer to the sender in a string instead of passing the actual class. For Example:

 

from django.apps import AppConfig
from django.db.models.signals import pre_save


class TestConfig(AppConfig):
      def read(self):
          # you can get the model like this
          Test = self.get_model('Test')
          pre_save.connect(receiver, sender='app_label.ModelName')

 

Application Registry

The application registry is the feature of Django that handles all the registration of apps. It provides the following methods:

  • ready: this is a boolean attribute with shows True when the AppConfig is ready.
  • get_app_configs(): this method returns an iterable of all AppConfig instances
  • get_app_config(app_label): this method provides AppConfig of the given app label. It raises LookupError if not AppConfig found.
  • is_installed(app_name): this method returns True if an app with the given name is installed in the registry. This method requires a full app name like ‘mysite.authentication’.
  • get_model(app_label, model_name, require_ready=True): this method returns a model class of given model name in the given app name. require_ready behaves the same as AppConfig.

Process of Loading Applications in Django

When Django starts, django.setup() is responsible for registering apps. This method configures Django by loading the settings, then it configures logging (if available) after that it initializes the application registries. This process is performed every time the Django server starts or when a management command is run.

The app registry is initialized in three steps for each app. First, Django imports each item in INSTALLED_APPS. At this stage, you won’t be able to import models from the app because the app registry is not populated yet. Django loads the app configurations in the same order as they are written in INSTALLED_APPS

After that, Django tries to import models of each app. At this stage, the methods like get_models and get_model become usable.

After the success of both steps, on the last step, the ready method of each app config is called.

 

Share this article

Related Posts