PyCharm 2024.1 Help

Create and use custom template tags

Enable the Django plugin

This functionality relies on the Django plugin, which is bundled and enabled in PyCharm by default. If the relevant features aren't available, make sure that you didn't disable the plugin.

  1. Press Ctrl+Alt+S to open settings and then select Plugins.

  2. Open the Installed tab, find the Django plugin, and select the checkbox next to the plugin name.

With Django you can set up a new tag to introduce a functionality that is not covered by the built-in template tags. PyCharm provides you with corresponding code and navigation assistance.

Create a custom template tag

  1. Under the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags.

  2. In the templatetags package, create a .py file, for example my_custom_tags, and add some code to it to declare a custom tag.

    For more information about custom template tags coding practices, refer to Django documentation.

    Adding a custom template tag

Add a custom template tag to a template

  1. Open you template file in the editor and add the corresponding template tag to it.

    Unresolved reference

    PyCharm displays the Unresolved tag inspection error because you have not loaded the custom tag into the template file.

  2. Use a quick-fix to resolve the missing reference. Place the caret at the custom tag name, press Alt+Enter, and select the file to load.

    Inspections to load a custom template

    PyCharm adds the {% load %} tag to the template file to fix the reference.

    Tag implementation name completion

PyCharm also recognizes custom template tags that are recorded as builtins tags in the TEMPLATES section of the settings.py file.

Navigating to the tag implementation

Once you record a custom tag in the settings file, you can navigate to the file with its declaration. Place the caret at the template tag filename and press Ctrl+B.

Last modified: 17 June 2024