Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Django, is it possible to access the current user session from context of parent template within a inclusion tag?
    primarykey
    data
    text
    <p>As we know, if we want to access user session from context within a inclusion tag, you can use <code>takes_context</code> argument and pass a request context in the view.</p> <p>But in my project, it is more complicated:</p> <p>The view is simple:</p> <pre><code># views.py def index(request): form = PersonForm() return render(request, 'add.html', {'form': form}) </code></pre> <p>Templates:</p> <pre><code># templates/add.html &lt;html&gt; &lt;head&gt; &lt;title&gt;Add Person&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form enctype="multipart/form-data" action="" method="post"&gt; {{ form.as_p }} &lt;/form&gt; {% render_attachments %} ... &lt;/body&gt; &lt;/html&gt; # templates/list.html {% load my_tags %} &lt;div class="attachments" style="margin:12px 0 12px 0;"&gt; {% for attachment in attachments %} &lt;a href="{{ attachment.attachment_file.url }}"&gt;{{ attachment.filename }} &lt;/a&gt; {% attachment_delete_link attachment %} {% endfor %} &lt;/div&gt; </code></pre> <p>Here is my custom tags:</p> <pre><code># 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} </code></pre> <p>When i run my project, i got the following error:</p> <pre><code>KeyError at /person/ 'user' Request Method: GET Request URL: http://localhost:8000/person/ Django Version: 1.5.1 Exception Type: KeyError </code></pre> <p>So, i print context out within two tags to find out what happened, it seemed that the request context does not passed into <code>attachment_delete_link</code>, how can i resolve this problem?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload