【问题标题】:In Django, is it possible to access the current user session from context of parent template within a inclusion tag?在 Django 中,是否可以从包含标记内的父模板上下文访问当前用户会话?
【发布时间】:2013-11-30 02:40:04
【问题描述】:

我们知道,如果我们想从包含标签中的上下文访问用户会话,您可以使用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,我该如何解决这个问题?

【问题讨论】:

  • 你在TEMPLATE_CONTEXT_PROCESSORS中有django.contrib.auth.context_processors.auth
  • 是的,我可以在第一个标签render_attachments 中获取用户,但在第二层,用户似乎迷路了。

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


【解决方案1】:

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

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

attachment_delete_link() 也是如此。

【讨论】:

    猜你喜欢
    • 2010-09-25
    • 2011-04-20
    • 2016-02-23
    • 2015-11-26
    • 2011-11-19
    • 2010-09-07
    • 1970-01-01
    • 2011-07-24
    • 2011-02-02
    相关资源
    最近更新 更多