Home > Back-end >  How to access the dictionary keys and values in django templates
How to access the dictionary keys and values in django templates

Time:01-14

I have created a dictionary of message senders which is updating dynamically. If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code;

views.py

def home(request):
    senders = {}
    chatting =Message.objects.filter(seen=False)
    for msg in chatting:
        user = User.objects.get(id=msg.sender.id)
        
        if user != request.user and  user  not in senders.values():
            senders.update({user.id : user})
                    
    return render(request, 'home.html', senders)

template Home.html

    <div>
            {% for key, val in senders %}
           
         
                <div>
                    <a href="#">{{val}}</a>
                </div>
                
            {% endfor %}
        </div>

CodePudding user response:

first of all, are you sure you really need a dict here? usually Django has a list of dicts. So, you loop just list, like here: https://github.com/ansys/aedt-testing/blob/cefebb91675dd54391d6324cd78e7bc97d9a8f6b/aedttest/static/templates/project-report.html#L220

however, answer to a direct question:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

CodePudding user response:

use below instruction in template of django :

{{ key }}: {{ value }}

  •  Tags:  
  • Related