Fire Assassin
Fire Assassin

Reputation: 59

Django - How do I display data from a dictionary from views to html file

I have a dictionary in my views.py that set up like this:

def dctFormat(request):
    dct = {}
    dct1 = {}
    for data in MapData.objects.all().iterator():
        dct[data.User_Number] = dct1
        dct1["First_Name"] = data.First_Name
        dct1["Account_or_Gift"] = data.Account_or_Gift
        dct1["Child_Name"] = data.Child_Name
    return render(request, 'datamap.html', context=dct)

In the model.py, the MapData model looks like this:

class MapData(models.Model): # name of the table
    AccountType = models.TextChoices('AccountType', 'Account Gift')
    UserType = models.TextChoices('UserType', 'User Customer')

    User_Number = models.IntegerField()
    User_or_Customer = models.CharField(max_length=8, choices=UserType.choices)
    First_Name = models.CharField(max_length=30);
    Child_Relationship_With_Gift = models.CharField(max_length=20)
    Child_Name = models.CharField(max_length=20)
    Account_or_Gift = models.CharField(max_length=10, choices=AccountType.choices)
    Occasion_or_Purpose = models.TextField()
    City_State = models.CharField(max_length=30)

How do I go about displaying the dictionary in my views.py on the front end in my HTML file? I've seen a few forums but none of them really helped. Essentially the dictionary should look like this:

{'1': {'First_Name': 'Paula', 'Child_Name': 'Ari', 'Account_or_Gift': 'Gift'},
'2': {'First_Name': 'Jake', 'Child_Name': 'Luke', 'Account_or_Gift': 'Account'}...}

So when I call on the dictionary, it'll display the data based on the corresponding number. This is what I tried:

{% for mapdata in dct %}
  <p>{{ mapdata.User_Number}}</p>
{% endfor %}

Upvotes: 1

Views: 673

Answers (1)

ErikR
ErikR

Reputation: 590

You cannot iterate over dct before you have made it a keyword in the context.

You can solve this by

    context = {'dct': dct}
    return render(request, "datamap.html", context)

And in your template:

  {% for user_number, mapdata in dct.items %}
    {{ user_number }}
    {{ mapdata.First_Name }}
  {% endfor %}

Upvotes: 2

Related Questions