0

I am new to Python/Django development, i want to loop through a dic value that i am sending from my view on my template but i can't get the value base on index/key. Kindly help me out.

My View

def contact(request):

    contactDetails = {
        'name': ['Adeola Ajayi', 'Olayemi'], 
        'email': ['a@gmail.com', 'b@gmail.com']
    }

    return render(request, 'PythonWeb/contact.html', 
        {'contactDetails':contactDetails})

My Template

{% block content %}
   <br><br>
    {% for contact in contactDetails%}
       <p> name: {{ contact.name }} </p>
       <p> name: {{ contact.email }} </p>
    {% endfor %}

{% endblock %}

This is how i want my template to display

name: Adeola Ajayi
email: a@gmail.com

name: Olayemi
email: b@gmail.com
xyres
  • 20,487
  • 3
  • 56
  • 85
  • Check this. https://stackoverflow.com/questions/8018973/how-to-iterate-through-dictionary-in-a-dictionary-in-django-template – Abdul Niyas P M Oct 04 '17 at 16:30
  • Do you have the option of changing the structure of contactDetails? Rather than a dict that contains lists (in your case, name is a list of two elements and email is a list of two elements) I would make contactDetails a list in which each element is a dict. i.e. rather than {'name': ['name1', 'name2'], email:['email 1', 'email 2']} I think this would be easier as [{'name':'name1', 'email':'email1'},{'name':'name2', 'email':'email2'}] Make sense? I don't have the ability to test the code here but, if you do this, I believe you'll get the result you want from your template. – Ben Oct 04 '17 at 16:56
  • Works fine.... Thanks – S.Olugbokiki Oct 05 '17 at 08:30

1 Answers1

0

You can create a zipped list and pass it to the template which will be a cleaner solution like this:-

zipped_list = zip(contactDetails['name'], contactDetails['email'])

and pass it to the template like this:-

return render(request, 'PythonWeb/contact.html', 
        {'contactDetails':zipped_list})

and implement it in template like this:-

{% block content %}
   <br><br>
    {% for name, email in contactDetails%}
       <p> name: {{ name }} </p>
       <p> name: {{ email }} </p>
    {% endfor %}

{% endblock %}

I hope it helps!

gautamaggarwal
  • 341
  • 2
  • 11