1

I am passing a dictionary to my template with this view - views.py

def personlist(request, id):
    data = requests.get('http://127.0.0.1:8000/app_name/cities/' + id + '/persons/').json()
    context = RequestContext(request, {
    'persons': data['results'],'count': data['count'],
})
    @register.filter(name='lookup')
    def cut(value, arg):
    return value[arg]
    {{ mydict|lookup:item.name }}

    return render_to_response('template.html', context)

where test_set is a dictionary inside results. I am using this view to render the template this way -

{% for person in persons %}
<a href="{% url 'person_detail' person.id %}"><p>{{person.name}}</p></a>
<p>{{person.test_set}}</p>
{% endfor %}

But that just displays the entire dictionary value - [{u'test_name': u'test', u'date': u'2015-12-15T20:57:51.556145Z'}] while I just want the date. I tried using a custom template to try and use person.test_set.date but it's not working.

Also, given the names and the dates is there a way to create a lookup to display names that were added on a daily/weekly/monthly basis?

WutWut
  • 1,204
  • 2
  • 17
  • 31

1 Answers1

1

You appear to be calling your custom template in the wrong way.

@register.filter(name='lookup')
def cut(value, arg):
    return value.get(arg, '{} not found'.format(arg))

{{ person.test_set|lookup:'date' }}

I've also modified the return value to return a message at least if it doesn't manage to find the key.


Your comment just made me realise that test_set isn't a dictionary, its a list of dictionaries. I'd imagine you want to iterate over these first then get the dates

{% for test in test_set %}
     {{ test.date }}
     {# or {{ test|lookup:'date' }} #}
{% endfor %}
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • Getting an error `'list' object has no attribute 'get'` – WutWut Dec 16 '15 at 08:21
  • @SaketMishra - Ah of course, I've updated my answer now – Sayse Dec 16 '15 at 08:23
  • Also could you give me a hint as to how I should proceed for the second part of my question? – WutWut Dec 16 '15 at 08:31
  • @SaketMishra - I'm not sure its pretty vague (perhaps make a new question but would need describing in more detail). I'd probably make a model in your database to store the test results correctly and then you can perform db filters etc – Sayse Dec 16 '15 at 08:38