Search code examples
djangodjango-templatesdjango-custom-tags

In Django, is it possible to access the current user session from context of parent template within a inclusion tag?


As we know, if we want to access user session from context within a inclusion tag, you can use takes_context argument and pass a request context in the view.

But in my project, it is more complicated:

The view is simple:

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

Templates:

# 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>

Here is my custom tags:

# 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}

When i run my project, i got the following error:

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

So, i print context out within two tags to find out what happened, it seemed that the request context does not passed into attachment_delete_link, how can i resolve this problem?


Solution

  • You are overwriting the whole context in render_attachments() you must return

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

    Same goes for attachment_delete_link().