在Django中,是否可以从包含标记内父模板的上下文访问当前用户会话?
如我们所知,如果我们想从包含标记中的上下文访问用户会话,您可以使用在Django中,是否可以从包含标记内父模板的上下文访问当前用户会话?,django,django-templates,django-custom-tags,Django,Django Templates,Django Custom Tags,如我们所知,如果我们想从包含标记中的上下文访问用户会话,您可以使用takes\u context参数并在视图中传递请求上下文 但在我的项目中,它更复杂: 观点很简单: # views.py def index(request): form = PersonForm() return render(request, 'add.html', {'form': form}) 模板: # templates/add.html <html> <head>
takes\u 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>
当我运行项目时,出现以下错误:
KeyError at /person/
'user'
Request Method: GET
Request URL: http://localhost:8000/person/
Django Version: 1.5.1
Exception Type: KeyError
因此,我在两个标记内打印出上下文以了解发生了什么,请求上下文似乎没有传递到
附件\u删除\u链接中,如何解决此问题?您在呈现附件()
中覆盖了整个上下文,您必须返回
def render_attachments(context):
# some code...
context['attachments'] = session.get('attachments', [])
return context
同样的情况也适用于attachment\u delete\u link()
您在模板\u context\u处理器中有django.contrib.auth.context\u处理器.auth
?是的,我可以在第一个标记呈现\u attachments
中获取用户,但在第二层中,用户似乎丢失了。
def render_attachments(context):
# some code...
context['attachments'] = session.get('attachments', [])
return context