5

I have a JSONField (http://djangosnippets.org/snippets/1478/) in a model and I'm trying to find out the best way to display the data to the admin user rather than json.

Does anyone know the best way to do this in django admin?

For instance, I would like

{u'field_user_name': u'foo bar', u'field_email': u'foo@bar.com'}

to display as

field_user_name = foo bar
field_email = foo@bar.com
kayluhb
  • 648
  • 7
  • 21
  • JSONField sholud in your case return valid Python dict i think. You can send that dict in your template and display it using template for loop for example. – Davor Lucic Jul 07 '10 at 23:02
  • Do you mean that you want to be able to modify this json field in admin app, by displaying it with another format ? – sebpiq Jul 08 '10 at 09:36
  • Sébastien -- no, I just want to display it in a friendly format from within the admin section, preferably without modifying templates. – kayluhb Jul 08 '10 at 14:39

2 Answers2

4

Perhaps create a custom widget?

class FlattenJsonWidget(TextInput):
    def render(self, name, value, attrs=None):
        if not value is None:
            parsed_val = ''
            for k, v in dict(value):
                parsed_val += " = ".join([k, v])
            value = parsed_val
        return super(FlattenJsonWidget, self).render(name, value, attrs)
Brandon Konkle
  • 737
  • 5
  • 9
0

Maybe you should create a template filter to do this :

from django import template
from django.utils import simplejson as json

register = template.Library()

@register.filter
def json_list(value):
    """
    Returns the json list formatted for display
    Use it like this :

    {{ myjsonlist|json_list }}
    """
    try:
        dict = json.loads(value)
        result = []
        for k, v in dict.iteritems():
            result.append(" = ".join([k,v]))
        return "<br/>".join(result)
    except:
        return value
Ghislain Leveque
  • 958
  • 1
  • 8
  • 21
  • 1
    This is great, but is there any way to do this without using templating? I would like to be able to use this in many different apps, but this approach could get cumbersome. – kayluhb Jul 08 '10 at 14:37