通过包含标记传递上下文变量

时间:2012-08-22 19:17:44

标签: python django django-custom-tags

执行检查以确定用户是否参加。如何在不is_attending的语法错误的情况下将上下文变量'is_attending': context['is_attending']传递给模板?检查基本上是为了设置div和诸如此类的东西。我做错了什么?

模板:

{% for event in upcoming %}
    {% registration %}

    {% if is_attending %}
         Registered!
    {% else %}
          Register button
    {% endif %}

    yadda yadda divs...
{% endfor %} 

filters.py

@register.inclusion_tag('events/list.html', takes_context=True)
def registration(context, event):
    request = context['request']
    profile = Profile.objects.get(user=request.user)
    attendees = [a.profile for a in Attendee.objects.filter(event=event)]
    if profile in attendees:
        'is_attending': context['is_attending']
        return is_attending
    else:
        return ''

谢谢!

1 个答案:

答案 0 :(得分:6)

'is_attending': context['is_attending']无效的python。相反,它看起来像一个部分字典。由于.inclusion_tag()代码应该返回一个字典,或许你的意思是:

if profile in attendees:
    return {'is_attending': context['is_attending']}
else:
    return {'is_attending': ''}

另请注意,takes_context表示您仅 将上下文作为参数。来自howto on custom tags

  

如果在创建模板标记时指定了takes_context,则标记将没有必需的参数,并且底层的Python函数将具有一个参数 - 从调用标记时开始的模板上下文。

因此你的标签应该是:

 {% registration %}

并且您的完整方法可以直接从上下文中获取event参数:

@register.inclusion_tag('events/list.html', takes_context=True)
def registration(context):
    request = context['request']
    event = context['event']
    profile = Profile.objects.get(user=request.user)
    attendees = [a.profile for a in Attendee.objects.filter(event=event)]
    if profile in attendees:
        return {'is_attending': context['is_attending']}
    else:
        return {'is_attending': ''}