1

我有两个模型news.article 和portfolio.entry。两个模型都有一个用于将“is_campaign”设置为 true 的 BooleanField。

我正在尝试编写自定义模板标签,以便获取最新的广告系列文章(应该只有一篇)

这是我的模板标签:campaign_article.py

from itertools import chain
from django import template

from news.models import Article
from portfolio.models import Entry

register = template.Library()

def get_campaign():
        #Get the newest news article with is_campaign=True
        article = Article.objects.filter(is_campaign=True).order_by('-pub_date')[:1]

        #Get the newest portfolio entry with is_campaign=True
        portfolio = Portfolio_entry.objects.filter(is_campaign=True).order_by('-pub_date')[:1]

        #combine article, and entry and display only the newest
        campaign_article = list(chain(article, portfolio))[:1]


        return {'campaign_article': campaign_article}



register.tag('campaign', get_campaign)

我在我的模板中试过这个:

{% load campaign_article %}
{% for campaign_article in campaign %}

{{ campaign_article.id }}

{% endfor %}

但我没有得到任何输出。这是错误的方法吗?

4

2 回答 2

1

您会想要创建assignment_tag而不是通用标签。因此,您可以将标签更新为:

def get_campaign():
    #your stuff
    ....

    return campaign_article

register.assignment_tag(get_campaign, name='campaign')

并将模板更新为:

{% load campaign_article %}
{% campaign as campaign_list %} {# loads the tags and creates campaign_list context variable #}
{% for campaign_article in campaign_list %}
    {{ campaign_article.id }}
{% endfor %}
于 2012-10-15T14:03:38.057 回答
0

你不需要创建模板标签来做你想做的事。阅读上下文处理器

def get_campaign(request): # this is your context processor            
        # ...    
        return {'campaign_article': campaign_article}

在您看来:

def some_view(request):
    # ...
    c = RequestContext(request, {
        'foo': 'bar',
    }, [get_campaign]) # attach your context processor to template context
    return HttpResponse(t.render(c))

UPD:如果您需要在每个页面上显示数据,您可以在您的设置文件中将您的上下文处理器注册为全局。请参阅模板上下文处理器设置。

TEMPLATE_CONTEXT_PROCESSORS = (..., "myapp.context_processors.get_campaign")

campaign_articleDjango 会自动为每个模板渲染添加变量。

于 2012-10-15T13:29:25.483 回答