pythondjangopostgresqldjango-jsonfield

How can i get values of JSONfield in my template


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


Solution

  • 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>