Django :第 121 行的无效块标签:"popular_products",预期的"结束块"。您是否忘记注册或加载此标签?



我的项目中有一个自定义模板标记,一切看起来都很好,但当我想使用这个模板标记时,我得到了这个错误:

第122行的块标记无效:"popular_products",应为"endblock"。你忘记注册或加载这个标签了吗?

base_tags.py:

from django import template
from django.db.models import Count, Q
from datetime import datetime, timedelta
from shop.models import Product
register = template.Library()

@register.inclusion_tag('shared/partials/popular_product_slider.html')
def popular_products():
last_week = datetime.today() - timedelta(days=7)
return {
"popular_products": Product.objects.filter(available=True).annotate(
count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by(
'-count', '-created')[:3]
}

home_page.html模板:

{% extends 'shared/_base.html' %}
{% load base_tags %}
{% load i18n %}
{% load render_partial %}
{% load static %}
{% load ratings %}
{% load thumbnail %}
{% block content %}
<div class="row">
<div class="col-lg-12">
<div class="tab-content">
<div id="recent" class="tab-pane fade show active">
<div class="row  product-slider">
{% popular_products %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}

popular_product_slider.html

{% for product in popular_products %}
{{product.image}}
{{product.detail}}
{{product.title}}
{% endfor %}

views.py

def home_page(request):
context = {}
return render(request, 'Home_page.html', context)


您需要将代码放在块中的home_page.html中。xxx是您放置在_base.html 中的块的名称

{% block xxx %}
<div class="row">
<div class="col-lg-12">
<div class="tab-content">
<div id="recent" class="tab-pane fade show active">
<div class="row  product-slider">
{% popular_products %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}

您错误地使用了{% popular_products %}。您应该使用{% include 'popular_product_slider.html' %}popular_product_slider.html实现为home_page.html

若使用带前导号({% %}(的花模板方括号,则第一个值将作为命令。并且该文件未将popular_products识别为命令,并引发了Error

相关内容

  • 没有找到相关文章

最新更新