Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

python - Pass a context variable through an inclusion tag

Performing a check to see whether or not a user is attending or not. How do I pass the context variable is_attending to the template without getting a syntax error on 'is_attending': context['is_attending']? The check is basically for styling divs and whatnot. What am I doing wrong?

template:

{% 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 ''

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'is_attending': context['is_attending'] is not valid python. Rather, it looks like a partial dictionary. Since .inclusion_tag() code is supposed to return a dict, perhaps you meant the following instead:

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

Also note that takes_context means you'll only take the context as an argument. From the howto on custom tags:

If you specify takes_context in creating a template tag, the tag will have no required arguments, and the underlying Python function will have one argument -- the template context as of when the tag was called.

Thus your tag should be:

 {% registration %}

and your full method can take the event argument directly from the context:

@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': ''}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...