Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Custom Tags

In this tutorial, we'll create a custom template tag in Django. Template tags allow you to implement custom logic and control structures in your templates, making them more dynamic and flexible.

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with Django framework
  • A Django project set up and running

Step 1: Create a Django app for your custom tags

1.1. Run the following command to create a new app called "mytags":

python manage.py startapp mytags

1.2. Add the new app to the INSTALLED_APPS list in myproject/settings.py:

INSTALLED_APPS = [
    # ...
    'mytags',
]

Step 2: Create the custom tag

2.1. In the "mytags" app, create a new directory named "templatetags":

mkdir mytags/templatetags

2.2. Inside the "templatetags" directory, create a new Python file named "custom_tags.py":

touch mytags/templatetags/custom_tags.py

2.3. Open "custom_tags.py" and define your custom tag function. For this tutorial, we'll create a tag that generates a random number within a specified range:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_number(low, high):
    return random.randint(low, high)

Step 3: Use the custom tag in a template

3.1. In one of your app's templates (e.g., myapp/templates/myapp/index.html), load the custom tag by adding the following line at the beginning of the template:

{% load custom_tags %}

3.2. Use the custom tag in the template. In this example, we'll generate a random number between 1 and 100:

{% load custom_tags %}

<p>Random number between 1 and 100: {% random_number 1 100 %}</p>

Step 4: Test the custom tag

4.1. Run your Django development server:

python manage.py runserver

4.2. Open your web browser and visit the page that uses the custom tag. The random number should be displayed on the page.

And that's it! You've created and used a custom template tag in Django. You can now create more custom tags to add more functionality and control structures to your Django templates. Remember to always register your custom tags with template.Library() and load them in your templates with the {% load %} tag.

  1. Creating custom template tags in Django:

    • Description: Django allows you to create custom template tags to perform complex logic in your templates.
    • Code Example:
      # myapp/templatetags/my_tags.py
      from django import template
      
      register = template.Library()
      
      @register.simple_tag
      def my_custom_tag():
          return "Hello from custom tag!"
      
      In your template:
      {% load my_tags %}
      <p>{% my_custom_tag %}</p>
      
  2. Django custom template tags and filters example:

    • Description: Custom template filters allow you to modify variables in your templates. Tags perform complex logic.
    • Code Example:
      # myapp/templatetags/my_filters.py
      from django import template
      
      register = template.Library()
      
      @register.filter(name='add_prefix')
      def add_prefix(value, prefix):
          return f"{prefix} {value}"
      
      In your template:
      {% load my_filters %}
      <p>{{ some_variable|add_prefix:"Hello" }}</p>
      
  3. How to use custom tags in Django templates:

    • Description: After creating custom tags, load them in your template using the {% load %} tag and use them as needed.
    • Code Example:
      {% load my_tags %}
      <p>{% my_custom_tag %}</p>
      
  4. Examples of custom tags in Django:

    • Description: Custom tags can range from simple display logic to more complex operations like querying the database.
    • Code Example:
      # myapp/templatetags/my_tags.py
      @register.simple_tag
      def get_latest_post():
          return Post.objects.latest('pub_date')
      
      In your template:
      {% load my_tags %}
      <p>Latest Post: {% get_latest_post %}</p>
      
  5. Django custom tag parameters:

    • Description: Custom tags can take parameters to make them more flexible. Define parameters in the tag function.
    • Code Example:
      # myapp/templatetags/my_tags.py
      @register.simple_tag
      def multiply(value, factor):
          return value * factor
      
      In your template:
      {% load my_tags %}
      <p>Result: {% multiply 5 3 %}</p>
      
  6. Debugging custom tags in Django templates:

    • Description: Use Django's template debugging techniques, like {% debug %}, to troubleshoot issues in custom tags.
    • Code Example:
      {% debug %}
      
  7. Reusable components with Django custom tags:

    • Description: Custom tags promote code reusability by encapsulating logic into reusable components.
    • Code Example:
      # myapp/templatetags/my_tags.py
      @register.inclusion_tag('myapp/my_component.html')
      def render_my_component(data):
          return {'data': data}
      
      In your template:
      {% load my_tags %}
      {% render_my_component some_data %}
      
      my_component.html:
      <p>{{ data }}</p>