在Django中,是否可以从包含标记中的父模板的上下文访问当前用户会话?

时间:2013-11-16 19:06:16

标签: django django-templates django-custom-tags

如我们所知,如果我们想要从包含标记中的上下文访问用户会话,您可以使用takes_context参数并在视图中传递请求上下文。

但在我的项目中,它更复杂:

观点很简单:

# views.py
def index(request):
    form = PersonForm()
    return render(request, 'add.html', {'form': form})

模板:

# templates/add.html
<html>
    <head>
        <title>Add Person</title>
    </head>
    <body>
        <form enctype="multipart/form-data" action="" method="post">
            {{ form.as_p }}
        </form>
        {% render_attachments %}
        ...
    </body>
</html>

# templates/list.html
{% load my_tags %}
<div class="attachments" style="margin:12px 0 12px 0;">
    {% for attachment in attachments %}
        <a href="{{ attachment.attachment_file.url }}">{{ attachment.filename }}
        </a>
        {% attachment_delete_link attachment %}
    {% endfor %}
</div>

这是我的自定义标签:

# my_tags.py

@register.inclusion_tag('attachments/list.html', takes_context=True)
def render_attachments(context):
    session = context['request'].session
    return {'attachments': session.get('attachments', [])}

@register.inclusion_tag('attachments/delete_link.html', takes_context=True)
def attachment_delete_link(context, attachment):
    if context['user'] == attachment.creator:
       return {
           'delete_url': reverse('delete_attachment', 
                                 kwargs={'attachment_pk': attachment.pk})
    }
    return {'delete_url': None}

当我运行我的项目时,我收到以下错误:

KeyError at /person/
'user'
Request Method: GET
Request URL:    http://localhost:8000/person/
Django Version: 1.5.1
Exception Type: KeyError

所以,我在两个标签内打印上下文以找出发生了什么,似乎请求上下文没有传递到attachment_delete_link,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您正在覆盖render_attachments()必须返回的整个上下文

def render_attachments(context):
    # some code...
    context['attachments'] = session.get('attachments', [])
    return context

同样适用于attachment_delete_link()