Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly unpack a nested dictionary in a django HTML template?

So I was able to figure out how to unpack a dictionary keys and values on to a HTML template, but I am a bit confused as to how to unpack if if a dictionary value is a QuerySet. For example I passing in all the timeslots of the given user into the dictonary. How can I unpack the attributes of the TimeSlot QuerySet for each timeslot such as the start time and end time?

This is my HTML Template:

<table>
    {% for key, value in user_info.items %}
        {% for key2,value2 in value.items %}
        <tr>
            <td>{{key2}}</td>
            <td>{{value2}}<td>
        </tr>
        {% endfor %}
        <br>
    {% endfor %}
    </table> 

My function in views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def check_food_availibility(request):
    food = FoodAvail.objects.all()
    timeslots = TimeSlot.objects.all()
    users_dict = {}
    for i in range(len(user_info)):
        user = {
            "author": None,
            "food_available": None,
            "description": None,
            "timeslot": None
        }
        user["author"] = user_info[i].author.username
        user["food_available"] = user_info[i].food_available
        user["description"] = user_info[i].description
        if TimeSlot.objects.filter(time_slot_owner=user_info[i].author):
            user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author)
        users_dict[user_info[i].author.username] = user

    return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict})

This is how it shows up currently:
enter image description here

>Solution :

try this

<table>
    {% for key, value in user_info.items %}
        {% for key2,value2 in value.items %}
        <tr>
            <td>{{key2}}</td>
          {% if key2 == 'timeslot' %}
           <td>
         {% for i in value2 %}

            i.start_time <-> i.end_time // just an example put your field here

         {% endfor %}
          
           </td>
          {% else %}
            <td>{{value2}}<td>
   
          {% endif %}
        </tr>
        {% endfor %}
        <br>
    {% endfor %}
    </table> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading