0

I've had a look at previous questions, and I'm unable to find an answer to my issue.
I'm trying to display a 2D list, which I have done earlier in the HTML with a different list. I've used a similar method for the other list but it wont display, I'm just getting the headers.
HTML:

    <table class="listtable" >
    <thead>
    <tr>
        <th>No</th>
        <th>Account No</th>
        <th>Time</th>
        <th>Message</th>
    </tr>
    </thead>
    {% for person in user %}
    <tr>
        {% for message in person %}
        <td>{% autoescape off %}{{ message }}{% endautoescape %}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

I've printed the list in the view, so I know that within the view it is correct. I am 100% sure that I've used the correct variables as well.
The code in the view is similar to:

user = get_data_from_other_source()
for item in user:
    print(item)

The print displays exactly what it should.
The list is along the lines off:

[4, '<account number>', '<time>', 'somestring']
[3, '<account number>', '<time>', 'somestring']

The page source says:

<table class="listtable" >
    <thead>
    <tr>
        <th>No</th>
        <th>Account No</th>
        <th>Time</th>
        <th>Messages</th>
    </tr>
    </thead>

</table>

EDIT: Moderated view code..

@login_required(login_url='/login')
def page_control(request):
    acc_no = request.session['acc_no']

    user = setup_page_control (acc_no)
    for item in user:
        print(item)
    return render_to_response("<htmlfile>.html",
                              locals(),
                              context_instance=RequestContext(request))



def setup_user_control(acc_no):
    messages = <outside magic>
    user = reversed(messages)
    return user

I have gutted a lot out of the code, and changed variable names etc.. I've only deleted stuff which I am 100% sure are not the problem

Maximas
  • 702
  • 2
  • 6
  • 16

3 Answers3

2

An explanation for the issue you found:

reversed() returns a reverse iterator. This is NOT the reversed list as you expect it to be:

>>> a = [1,2,3,4,5]
>>> print reversed(a)
<listreverseiterator object at 0x...>

As you can see, reversed(a) is not the list in reverse, but the actual iterator itself. In order to get the reversed list like you want you can use:

user = list(reversed(messages))
# or
user = messages[::-1]

(source: How can I reverse a list in python?)

Community
  • 1
  • 1
pcoronel
  • 3,833
  • 22
  • 25
0

I believe your response should be like this:

 return render_to_response("<htmlfile>.html",
                          {'user':user},
                          context_instance=RequestContext(request))
petkostas
  • 7,250
  • 3
  • 26
  • 29
0

I've found my issue, but I'm not sure why it happened. When I removed:

user = reversed(messages)

The template was willing to output the list again. Awfully odd. If anyone knows why, it would be great for an explanation :)

Maximas
  • 702
  • 2
  • 6
  • 16