Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TypeError: __init__() missing 1 required positional argument: 'loaders'

Django's Cached Template Loader

Quick tip on fixing an error that may confuse you. Namely, because in the settings file, we have to give string names - so errors are somewhat abstracted from your input.

Basically, when you give the argument to TEMPLATES["OPTIONS"]["loaders"],

  • the argument is a list of loaders;
  • for the cached loader, the first argument is the cached loader,
  • but it needs 1+ args - what it's caching.
  • You pass this as a tuple of the loader, and its args.

Docs

If you get it mixed up, there are a few different errors - this is one:

TypeError: __init__() missing 1 required positional argument: 'loaders'

Incorrect:

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [...],
        "OPTIONS": {
            "context_processors": [...],
            "loaders": (
                # XXX The nesting is INCORRECT
                "django.template.loaders.cached.Loader", 
                    "django.template.loaders.filesystem.Loader",
                    "django.template.loaders.app_directories.Loader",
                ),
            ),
        },
    }
]

Correct:

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [...],
        "OPTIONS": {
            "context_processors": [...],
            "loaders": [
                ("django.template.loaders.cached.Loader", [
                    "django.template.loaders.filesystem.Loader",
                    "django.template.loaders.app_directories.Loader",
                ]),
                # ('foobar.Loader', ['arg1', 'arg2']),
            ],
        },
    }
]

Or in case it clarifies, here's different formatting:

            "loaders": [
                    ("django.template.loaders.cached.Loader", ["django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader"]),
                    # "another.hypothetical.Loader",
                    # ("yet.another.example.Loader", [arg, arg2, arg3]),
            ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.