I have a view that has context data and it extends base.html but as I want the context data to be displayed in all templates that extend from base.html and not only the view with the context data I am doing custom template tags with the context inside but I get an error.
view with and without context data:
class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
paginate_by = 25
class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
paginate_by = 25
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
categories = Category.objects.all()
news = News.objects.all()
context.update({
'categories' : categories,
'news' : news,
})
return context
base.html with and without the custom tag
{% news %}
{% for new in news %}
<p>{{ new.title }}</p>
{% endfor %}
The custom tag file templatetags/news.py
from django import template
from support.models import News
register = template.Library()
@register.inclusion_tag('news.html', takes_context=True)
def news(context):
return {
'news': News.objects.order_by("-date_posted")[0:25],
}
The custom tag file templatetags/news.html
{% for new in news %}
<p>{{ new.title }}</p>
{% endfor %}
CodePudding user response:
Simple thing, you should load
the template tag in news.html template which is registered.
Just load the tag in news.html
template:
{% load tag_name %} #Add here tag name to load
Note: Please ensure that template tag setting is added in settings.py file
CodePudding user response:
You need to define the python code containing your tag codes in the TEMPLATES
variable in settings.py
.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(BASE_DIR.joinpath('templates'))
],
'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',
],
'libraries':{
'tagname': 'appname.news', # your template tag
}
},
},
]