ilyas Jumadurdyew
ilyas Jumadurdyew

Reputation: 930

parse and order csv file in django template

How to parse csv file into django template and sort them by:

myfile.csv

status, date, user, rating

Registered, 12-10-2016, user1, 8.75

Registered, 22-05-2016, user2, 9.23

Registered, 19-11-2016, user3, 7.00

Currently i'm trying to do things like this:


Views.py

args = {}
file_url = urllib2.Request("http://server.local:8000/static/myfile.csv", None, {'User-Agent': 'Mozilla/5.0'})
file_url_response = urllib2.urlopen(file_url)
pre_reader = csv.reader(file_url_response)
args['list'] = pre_reader
return render_to_response('template.html', args)

template.html

{% for row in list %}
<p>
    {% for item in row %}
        {{ item }}
    {% endfor %}
</p>
{% endfor %}

Rendered HTML response is:

status, date, user, rating

Registered, 12-10-2016, user1, 8.75

Registered, 22-05-2016, user2, 9.23

Registered, 19-11-2016, user3, 7.00


But I want to do something like this:

<table>
{% for row in list %}
<tr>
    <td>
        {{ row.status }}
    </td>
    <td>
        {{ row.date }}
    </td>
    <td>
        {{ row.user }}
    </td>
    <td>
        {{ row.rating }}
    </td>
</tr>
{% endfor %}
</table>

Also it would be great If I could order by values, so users can order results by date or by rating

Upvotes: 2

Views: 1035

Answers (2)

Tiny.D
Tiny.D

Reputation: 6556

You can use something like {{row.0}}, see Variables and lookups, just change your template to template.html:

<table>
{% for row in list %}
<tr>
    <td>
        {{ row.0 }}
    </td>
    <td>
        {{ row.1 }}
    </td>
    <td>
        {{ row.2 }}
    </td>
    <td>
        {{ row.3 }}
    </td>
</tr>
{% endfor %}
</table>

Upvotes: 0

Andrey Shipilov
Andrey Shipilov

Reputation: 2014

In your view function do this.

...
csv_dict = {rows[0]:rows[1] for rows in pre_reader}
args['csv_dict'] = csv_dict
...

Then you will have a dict in your template that you can reorder using regroup tag. https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#regroup

Upvotes: 2

Related Questions