M
M
MrDoSSSS2017-07-04 11:21:53
Django
MrDoSSSS, 2017-07-04 11:21:53

How to correctly declare a custom tag in Django?

Good day!
Declared a custom tag in jang but nothing happens when used. Nothing is displayed, but there are no errors either. How to correctly declare custom tags?

# app/templatetags/extratags.py

from django import template
from app.models import Product

register = template.Library()

@register.simple_tag
def get_lenta_elem():
    items = Product.objects.all()
    return items

{% load extratags %}
<div class="lenta-elem-container">
    {% for elem in get_lenta_elem %}
    <div class="lenta-elem">
        <img src="{{ elem.image.url }}" alt="{{elem.name}}">
    </div>
    {% endfor %}
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2017-07-04
@ATNC

In order to make a tag available in all views, you can add it to the templates' nettings.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
           'builtins': 'app.templatetags.extratags' # <<<<<<<<<<<<<<<
        },
    },
]

But the global context is better for solving this problem.
def get_lenta_elem(request):
    items = Product.objects.all()
    return  {'items': items }

and in settings.py add a function to the global context
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # custom context processor
                'путь_к_файлу.навание_метода' # <<<<<<<<<<<<<
            ],
        },
    },
]

After that, the items variable will be available in all views.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question