7

I tried to find the answer but couldn't. In my template when I iterate over JSONfield

{%  extends "electronic/electronic_base.html" %}
{% load staticfiles %}
{% block content %}
{% for item in micro_all %}
<h1>{{item.title}}</h1>
<table class="table table-condensed">
<tbody>
<tr>
{% for key in item.attributes%}
<td>{{key}}</td>
{% endfor %}
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}

I can get the key, but not value. Tried to use key, value and print value but for some reasons it gave me single letters not even in the table format. How can I access values in the template

from django.db import models
from django.contrib.postgres.fields import JSONField

class Category(models.Model):
    title = models.CharField(max_length = 200)
    def __str__(self):
        return self.title

class SubCategory(models.Model):
    title = models.CharField(max_length = 200)
    category = models.ForeignKey(Category)
    def __str__(self):
        return self.title  

class Product(models.Model):
    title = models.CharField(max_length = 200)
    category = models.ForeignKey(Category)
    subcategory = models.ForeignKey(SubCategory)
    description = models.TextField(blank = True)
    attributes = JSONField()
    date = models.DateTimeField('дата добавления')

    def __str__(self):
        return self.title

This is my models.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Product, Category, SubCategory

def electronic_micro(request):
    micro_all =   Product.objects.filter(category__title__icontains="Микросхемы")
    return render(request,'electronic/micro_all.html', {'micro_all': micro_all})

def electronic_base(request):
    return render (request, "electronic/electronic_base.html")

This is my views

Ulvi
  • 965
  • 12
  • 31
Valery Lukin
  • 85
  • 2
  • 5
  • can you also add the print of your `JSONField` ? –  Jul 03 '16 at 10:16
  • it is just simple key:value features of the products for website. Strings and digits. if i try print {{item.attributes}} in template it prints everything as supposed to. Just can't get only values that i need to fill the rest of my table with – Valery Lukin Jul 03 '16 at 10:21

1 Answers1

12

You should be able to iterate it as a normal dictionary:

<table>
{% for key,value in item.attributes.items %}
    <tr>
        <td>{{key}}</td><td>{{value}}</td>
    </tr>
{% endfor %}
</table>