Coder Social home page Coder Social logo

kevinmickey / django-prettyjson Goto Github PK

View Code? Open in Web Editor NEW
139.0 4.0 21.0 360 KB

Enables pretty JSON viewer in Django forms, admin, or templates

License: BSD 3-Clause "New" or "Revised" License

Makefile 9.70% Python 43.93% CSS 5.99% JavaScript 36.31% HTML 4.07%

django-prettyjson's Introduction

django-prettyjson

PyPi Version Build Status

Enables pretty JSON viewer in Django forms, admin, or templates. The viewer is adapted from jQuery JSONView. It is compatible with almost anything: JSON stored in a string, a jsonfield (using django.contrib.postgres or django-jsonfield), or any python object that can be serialized to JSON (using standardjson).

Demo

See http://kevinmickey.github.io/django-prettyjson

Installation

At the command line:

pip install django-prettyjson

Configuration

Add 'prettyjson' to INSTALLED_APPS in settings.py:

INSTALLED_APPS = (
  ...,
  'prettyjson',
)

Usage

In a form or admin of a model, enable a pretty JSON viewer for a particular field:

from prettyjson import PrettyJSONWidget

class JsonForm(forms.ModelForm):
  class Meta:
    model = Test
    fields = '__all__'
    widgets = {
      'myjsonfield': PrettyJSONWidget(),
    }

class JsonAdmin(admin.ModelAdmin):
  form = JsonForm

Enable pretty JSON viewer for every JSONField of a model:

from django.contrib.postgres.fields import JSONField

class JsonAdmin(admin.ModelAdmin):
  formfield_overrides = {
    JSONField: {'widget': PrettyJSONWidget }
  }

In templates, you can also enable a pretty JSON viewer. Use the prettyjson template tag with a string JSON or with objects (dicts, QuerySets, etc.) that can be serialized to a JSON. Note that the template tag must be loaded using {% load prettyjson %}. It also has CSS and JS that must be included using {% prettyjson_setup %}.

{% extends "base.html" %}

{% load prettyjson %}

{% block header %}
  {{ block.super }}
  {% prettyjson_setup %}
{% endblock %}

{% block content %}
  {% prettyjson myqueryset %}
  {% prettyjson mydict %}
  {% prettyjson '{"hey": "guy","anumber": 243,"anobject": {"whoa": "nuts","anarray": [1,2,"thr<h1>ee"], "more":"stuff"},"awesome": true,"bogus": false,"meaning": null, "japanese":"明日がある。", "link": "http://jsonview.com", "notLink": "http://jsonview.com is great"}' %}
  {% prettyjson '{}' %}
{% endblock %}

The setup includes jQuery, loaded as django.jQuery to avoid namespace conflict. If your page already includes jQuery, use {% prettyjson_setup jquery=False %} to avoid loading jQuery a second time.

Configure Rendering

By default the jsonwidget will render as a raw string with a button to click to change it to parsed json. For it to render as parsed json initially, you can pass an argument:

class JsonAdmin(admin.ModelAdmin):
  formfield_overrides = {
    JSONField: {'widget': PrettyJSONWidget(attrs={'initial': 'parsed'})}
  }

Or, in a template tag:

{% prettyjson mydict initial='parsed' %}

Running Tests

In development.

source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install -r requirements-test.txt
(myenv) $ python runtests.py

Credits

Dependencies, parts of code, and/or sources of inspiration:

Tools used in developing, testing, and/or rendering this package:

django-prettyjson's People

Contributors

bpartridge avatar codemac avatar fcurella avatar kevinmickey avatar sdeprez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-prettyjson's Issues

Feature idea/request: sort keys alphabetically

I've been integrating with django-prettyjson and in some of my fields the ability to auto sort by key alphabetically in the parsed ("pretty") view would make it even prettier.

  1. Was this considered?
  2. Would you be open to a PR with a new class that inherit PrettyJson and adds the alphabetic sort?

Thanks for the great library :)

*Quick* Parsed JSON in Template

I can't seem to figure out how to do
`
{% load prettyjson %}
{% prettyjson_setup %}

{% prettyjson mydict %}

` and just show the json already pretty-fied/rendered ?

Help pls!

Option to start collapsed?

Thanks for this very nice and useful widget! I'm pretty certain, by looking at the doc and code, that there is no option to start the widget not only "parsed", but also "collapsed": if that's the case, and that my assumption that it would be fairly easy to do is correct, would you accept a PR for doing so?

The formatting does not work on read-only fields

My code setup is as follows:

models.py

class MyModel(models.Model):
    structure = JSONField(default=dict, blank=True, null=True)
    static_structure = JSONField(default=dict, blank=True, null=True, editable=False)

admin.py

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        JSONField: {'widget': PrettyJSONWidget }
    }

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('static_structure')
        else:
            return super(MyModelAdmin, self).get_readonly_fields(request, obj)

admin.site.register(MyModel, MyModelAdmin)

In other words, one of the JSONFields is not editable and read-only. It appears on my admin panel, but its not being affected by the widget which renders the other field as formatted JSON.

Is this by design? And is there any way to have the formatting work for read-only fields?

conflict with django-debug-toolbar

Using 0.2.1 on Django 1.10.5, when I enable the debug toolbar, the JSON widgets print text from DJANGO settings. It does not happen for every widget, but I have pages with many JSON Widgets and it happens on every page load.

Disabling the toolbar and everything goes back to normal.

I have not investigated further but thought this may save someone some time.

Does not align with other fields

It does not seem to align with the rest of the fields on the Admin form. Instead it aligns itself from the left of the form. It might be related to changes in Django.
align

  • Django: 2.0.2
  • django-prettyjson: 0.3.0

DjangoJSONEncoder instead of standardjson?

would it not be possible to use DjangoJSONEncoder instead of standardjson?

class DjangoJSONEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time, decimal types, and
    UUIDs.
    """

I18n

Can the strings be translatable please?

I was hoping I could at least replace a template file but the button strings are hard-coded in the js file.

It would be better if this could be translatable in a way or another…

standardjson is required

standardjson should be required when it is installed.

Invalid template library specified. ImportError raised when trying to load 'prettyjson.templatetags.prettyjson': No module named standardjson

Widget Within Table Row?

Wondering if it's possible to incorporate this "in row" within a table. As an example if you have a column within your table that is json, can we include an inline widget for each row & json cell to format.

PrettyJSONWidget() does not return form error test

Hello, I noticed that when you are returning a custom error in a ModelForm that uses the PrettyJsonWidget(), there is an indication that there is an error in that field, but it does not show the error message. In my use case I am overriding the clean() method on the ModelForm and using the add_error() method to return a custom error message on the field. When I use a TextField instead of the PrettyJsonWidget the error shows up, but does not when I am using the supplied widget.

Script run order problem

I'm using django-prettyjson with Django 2.0 and there seems to be a problem with the order in which the scripts are running. The prettyjson.js file is getting run before the Django jQuery gets loaded and so it throws an error. I was able to fix it with the following snippet:

class FixedPrettyJSONWidget(PrettyJSONWidget):
    class Media:
        js = ('admin/js/jquery.init.js', 'prettyjson/prettyjson.js', )
        css = {
            'all': ('prettyjson/prettyjson.css', )
        }

I'm not sure if there is a better way to do it, but hopefully this illustrates the problem.

Module six should be included in the requirements

Module six should be included in the requirements as it is required in 'prettyjson.templatetags.prettyjson'
Had ImportError when adding 'prettyjson' to installed apps on django 1.10.5 and python 3.5.2

Parsed widget size

When loading the widget as initially parsed in the admin, it takes the width and height of the original textarea, making it often too small. The parsed view takes considerably more space, and will often result in unnecessary scrolling:

screen shot 2017-08-30 at 10 52 38 am

This is easily fixable in the js, and I've got a fix ready. But I was wondering if you were set on the current behavior, of it there was a specific reason for how it currently works.

edit format needed without quotes

If I have ["HH"] stored in a jsonfield, when I edit the corresponding model, using django-prettyjson shows it with backslashes in attached screenshot

screen shot 2018-07-07 at 6 56 51 pm

When user saves the same string again, the backslashes become part of the json data. This means everytime a user clicks on change form to edit some other field, the json field will continue to get backslashes added.

This is not a good experience. Ideally, there should be a conversion to show string without backslashes to the user

Not work with readonly_fields

Using 0.2.2 on Django 1.9.4
It seems to not work with readonly_fields.

I think PrettyJSONWidget's render may run before render readonly_fields.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.