About Dynamic Class or Function Loading

For reusable apps, you can easily make some classes or functions overwritable in the settings, by defining their paths there. You can load them with the import_string() utility.

registration/views.py

1
2
3
4
5
6
7
8
from django.conf import settings
from django.utils.module_loading import import_string
from .forms import DefaultRegistrationForm

if hasattr(settings, "REGISTRATION_FORM"):
    form_class = import_string(settings.REGISTRATION_FORM)
else:
    form_class = DefaultRegistrationForm

settings.py

1
REGISTRATION_FORM = "accounts.forms.CustomRegistrationForm"

Tips and Tricks Programming Architecture Django 4.x Django 3.2 Django 2.2 Python 3