Giter Club home page Giter Club logo

django-json-widget's People

Contributors

amarsahinovic avatar ashokdelphia avatar barseghyanartur avatar cfculhane avatar d3x avatar dadokkio avatar dependabot[bot] avatar jmrivas86 avatar lingster avatar pedroma avatar stefanw avatar stevenmapes avatar travijuu avatar vinaypai avatar wqyjh 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  avatar  avatar  avatar

django-json-widget's Issues

Explicitly concatenate `settings.STATIC_URL` with the URL could cause problems when serving static files.

  • django-json-widget version: 0.1.1
  • Django version: 2.0.6
  • Python version: 3.5.2
  • Operating System: macOS High Sierra

Description

I have a custom version of ManifestStaticFilesStorage that removes the non-hashed files when calling collectstatic.
The widget concatenates settings.STATIC_URL to the URL pointing to the static files. This means that the hash created by the files storage will be ignored and a 404 will be returned as a result.

This is a specific case, but I think in general it's not a good practice to hardcode/concatenate URLs like that.

What I Did

Happy to create a PR to fix this, it's a very small change.

ReferenceError: JSONEditor is not defined In production

  • django-json-widget version: 2.0.1
  • Django version: 2.2.28
  • Python version:3.7
  • Operating System:Ubuntu

Description

It's working as expected in local but when I am trying to run it on production for postgres json fields, it's showing blank and in the console it's throwing the error ReferenceError: JSONEditor is not defined

Getting render() got an unexpected keyword argument 'renderer' in Django 2.1.1

  • django-json-widget version: 0.1.1
  • Django version: 2.1.1
  • Python version: 3.6.5
  • Operating System: MacOS High Sierra 10.13.6

Description

Getting error when following the default installation instructions.

TypeError at /admin/core/user/5/change/
render() got an unexpected keyword argument 'renderer'

What I Did

Steps to reproduce:

  1. pip install django-json-widget
  2. settings.py
    ...
    'django_json_widget',
    ...
]
  1. admin.py
from django_json_widget.widgets import JSONEditorWidget

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

@admin.register(DuitUser)
class UserAdmin(JsonAdmin):
    list_display = ('first_name', 'last_name', 'mobile_number')
  1. Open localhost:8000/admin in browser. You should see the error Exception Value: | render() got an unexpected keyword argument 'renderer'

Possible reasons

This is almost certainly because of this backwards-incompatible change in Django 2.1.
https://stackoverflow.com/a/52039655/842837

Collectstatic broken in 0.3.0+

  • django-json-widget version: 0.3.0, 1.0
  • Django version: 2.2.9
  • Python version: 3.6.9
  • Operating System: Ubuntu

Description

After upgrading from 0.2.0 collectstatic fails with an exception when STATICFILES_STORAGE is set to ManifestStaticFilesStorage.

What I Did

python manage.py collectstatic --noinput
Traceback (most recent call last):
  File "manage.py", line 35, in <module>
    execute_from_command_line(sys.argv)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
    django.setup()
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready
    self.module.autodiscover()
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/circleci/project/venv/lib/python3.6/site-packages/suit/admin.py", line 192, in <module>
    from cms.admin.forms import PageForm
  File "/home/circleci/project/cms/admin.py", line 5, in <module>
    from core.admin.filters import RawIDListFilter
  File "/home/circleci/project/core/admin/__init__.py", line 3, in <module>
    from core.admin.models import (
  File "/home/circleci/project/core/admin/models/__init__.py", line 21, in <module>
    from core.admin.widgets import JSONEditorWidget
  File "/home/circleci/project/core/admin/widgets.py", line 4, in <module>
    from django_json_widget.widgets import (
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django_json_widget/widgets.py", line 8, in <module>
    class JSONEditorWidget(forms.Widget):
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django_json_widget/widgets.py", line 9, in JSONEditorWidget
    class Media:
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django_json_widget/widgets.py", line 10, in Media
    css = {'all': (static('dist/jsoneditor.min.css'), )}
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/templatetags/static.py", line 167, in static
    return StaticNode.handle_simple(path)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/templatetags/static.py", line 118, in handle_simple
    return staticfiles_storage.url(path)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 153, in url
    return self._url(self.stored_name, name, force)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 132, in _url
    hashed_name = hashed_name_func(*args)
  File "/home/circleci/project/venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name
    raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for 'dist/jsoneditor.min.css'

Suspected

I believe the issue was introduced by 42b2c76. According to django documentation, Media class should use relative paths instead of resolving them with static().

Its no work when you make your model admin readonly

  • django-json-widget version: 1.1.1
  • Django version: 4.0.7
  • Python version: 3.9
  • Operating System: ubuntu 20.04

Description

when I make my model readonly widget not work !

`class ReadOnlyAdminModel(admin.ModelAdmin):
formfield_overrides = {
models.JSONField: {'widget': JSONEditorWidget},
}

def has_add_permission(self, request):
    return False

def has_change_permission(self, request, obj=None):
    return False

def has_delete_permission(self, request, obj=None):
    return False

`

What I Did

Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.

Django 3.2 Support Dark Theme

Hello, since Django 3.2, the admin panel support dark theme. When using a dark them, this widget is impossible to read in the tree mode. With #56, could you add the required CSS to have dark theme enabled widget?

Thanks

[Feature Request] Dark theme support

  • django-json-widget version: 2.0.1
  • Django version: 5.0.2
  • Python version: 3.12
  • Operating System: -

Description

The editor is burning my eyes. I would love to see the editor in a dark theme whenever Django admin is on dark mode.
image

What I Did

I might adjust some CSS to temporarily save my eyes.

Add Dark mode support

  • django-json-widget version:
  • Django version:
  • Python version:
  • Operating System:

Description

Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.

What I Did

Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.

v1.1.0 seems to be trying to use incorrect static files

  • django-json-widget version: v1.1.0
  • Django version: 3.1
  • Python version: 3.7
  • Operating System: Linux

Description

Just upgrade to Django v3.1 and with it, to django-json-version 1.1.0. After I run collectstatic, I get the following two files under my statics directory

  • dist/jsoneditor.min.css
  • dist/jsoneditor.min.js

which seems to be the same as version v1.0.1.

The problem is that when running the server, the page fails to load. Looking at the browser console, I can see it is erroring out trying to find dist/jsoneditor.css and dist/jsoneditor.js (see how it is not the .min. version)

image

What I Did

I didn't do anything different, so unless something changed in the way Django 3.1 works, this may be a problem with the new v1.1.0 version

JSONField not set to null after being set to empty

  • django-json-widget version: master/325ad3027b3915a2d41552c6e113453a9e56dd05 and 0.2.0
  • Django version: 2.2.4
  • Python version: 3.7.2
  • Operating System: Debian Stretch

Description

To reproduce:

  • Enable JSONEditorWidget on a JSONField in admin
  • Set JSONField value in admin to some non-empty json.
  • Save model in admin
  • Set the JSONField to empty by clearing the contents of the widget completely.
  • Save model in admin

What happens: The field does not get changed, it is still set to the original non-empty json and no error is displayed.

What I expected to happen: I expected the field to get set to null/None or I expected to at least get an error that the update to the field failed.

</script> is a problem

  • django-json-widget version: 1.1.1
  • Django version: 4.2.3
  • Python version: 3.11
  • Operating System: N/A

Description

I tried to show a json widget. But it was broken. Then I discovered that it was one of the fields inside my json that had the content </script>. Something like:

{"html": "<p>A paragraph</p><script>const a = 10;</script>"}

The issue is this: The </script> makes the script used by django-json-widget end immediately there. So the reminder of the json is rendered into the browser and the json widget throws an error in the JavaScript developer console.

Major Security Issue

  • django-json-widget version: 1.1.1
  • Django version: 3.2.8
  • Python version: 3.9.6
  • Operating System: Mac OSX

Description

This library isn't safe to use, I could inject a javascript code in it and it rendered to my admin view which might allow hackers to have access to all my admin capabilities.

This issue makes the whole library unusable to me especially that the json data we're storing are coming from parties we can't trust.

What I Did

[.] I put a javascript code in the json field I have. e.g. <script> alert('hi'); </script>
[.] Set the widget for that field to be JSONEditorWidget on admin
[.] Opened the change page for the object with that field, and the javascript was executed, which shouldn't

I think the cause of the issue is the following code in the library:
As you can see, you use |safe on the value of the widget, which you shouldn't do. I've tried removing the |safe filter but that made the json to not load at all!

<div {% if not widget.attrs.style %}style="height:{{widget.height|default:'500px'}};width:{{widget.width|default:'90%'}};display:inline-block;"{% endif %}{% include "django/forms/widgets/attrs.html" %}></div>

<textarea id="{{widget.attrs.id}}_textarea" name="{{ widget.name }}" required="" style="display: none">{{ widget.value }}</textarea>

<script>
    (function() {
        var container = document.getElementById("{{ widget.attrs.id }}");
        var textarea = document.getElementById("{{widget.attrs.id}}_textarea");

        var options = {{ widget.options|safe }};
        options.onChange = function () {
            var json = editor.get();
            textarea.value=JSON.stringify(json);
        }

        var editor = new JSONEditor(container, options);
        var json = {{ widget.value|safe }};
        editor.set(json);
    })();
</script>

Add additional maintainers

  • django-json-widget version: n/a
  • Django version: n/a
  • Python version: n/a
  • Operating System: n/a

Description

Hi @jmrivas86 - I've noticed that there are a lot of outstanding pull requests, including one which fixes a security vulnerability.

I understand that it's difficult to stay on top of maintaining all your OSS libraries, but I would be willing to help either do that or have someone from my team help out if you're willing to let us.

Perhaps we could have a discussion and you could add me as a maintainer to help get these issues fixed? An alternative would be transferring the entire repository to jazzband where the community can contribute to it; I could help with that too if you want.

Are you interested?

Unable to edit form field

  • django-json-widget version: 1.0.1
  • Django version: 3.0.3
  • Python version: 3.6
  • Operating System: Ubuntu 18.04

Description

I followed the instructions to get a basic example working.
The field is editable in the admin interface but is not editable from within a ModelForm. A large textarea field is displayed in the HTML form but no data is shown or split.

What I Did

forms.py

class DataTestForm(ModelForm):
    class Meta:
        model = DataTest
        exclude = ["slug"]
        widgets = {"eeg": JSONEditorWidget}

models.py

def facilities_imaging():
    return {"nonessions": 0, "esthourspermonth": 0}

class DataTest(Model):
    eeg = JSONField(blank=True, null=True, default=facilities_imaging)    # also tried without a default

form.html

# tried all separately
{{ form.eeg|as_crispy_field }}
{{ form.as_p }}

page source (eeg form field)

    <div id="div_id_eeg" class="form-group">
        
            <label for="id_eeg" class="">
                Eeg
            </label>
                <div class="">
                    <div style="height:500px;width:90%;display:inline-block;" class="jsoneditorwidget form-control" id="id_eeg"></div>
​
<textarea id="id_eeg_textarea" name="eeg" required="" style="display: none">{&quot;nonessions&quot;: 0, &quot;esthourspermonth&quot;: 0}</textarea>    # removing style shows the raw json
​
<script>
    (function() {
        var container = document.getElementById("id_eeg");
        var textarea = document.getElementById("id_eeg_textarea");
​
        var options = {"modes": ["text", "code", "tree", "form", "view"], "mode": "code", "search": true};    # tried changing modes
        options.onChange = function () {
            var json = editor.get();
            textarea.value=JSON.stringify(json);
        }
​
        var editor = new JSONEditor(container, options);
        var json = {"nonessions": 0, "esthourspermonth": 0};
        editor.set(json);
    })();
</script><input type="hidden" name="initial-eeg" value="{&quot;nonessions&quot;: 0, &quot;esthourspermonth&quot;: 0}" id="initial-id_eeg">
                </div>
    </div>

JSONEditor library not loaded in form assets

  • django-json-widget version: master
  • Django version: 2.2.12
  • Python version: 3.x

When using the JSONEditor widget on a basic modelform (non-admin page), the JSONEditor library is not loaded, resulting in the following javascript error:

Uncaught ReferenceError: JSONEditor is not defined

Suggestion to use get/setText() instead of get/set() to avoid weird save/error issues

options.onChange = function () {
    var json = editor.get();
    textarea.value=JSON.stringify(json);
}

The above piece of code has nasty behavior. According to json-editor docs, editor.get() throws an Exception when the editor doesn't contain a valid JSON value. Well, what are the implications? It saves the last valid JSON value. Few open issues are due to this behavior. For instance consider, #26 On the second attempt when clearing completely (assuming CTRL + A and Backspace), onChange triggers, and editor.get() throws exception failing to update widget.value. #47 The last known value in textarea.value is "", copy-pasting invalid json does not update its value due to the same reasons mentioned.

Possible Solution:

Changing <script> block in django_json_widget.html

<script>
    (function() {
        const container = document.getElementById("{{ widget.attrs.id }}");
        const textarea = document.getElementById("{{ widget.attrs.id }}_textarea");

        const options = {{ widget.options | safe }};
        options.onChange = function () {
            textarea.value = editor.getText();
        }

        const editor = new JSONEditor(container, options);

        const json = textarea.value;
        editor.setText(json);
        document.getElementById("{{ widget.attrs.id }}").getElementsByClassName('jsoneditor-format')[0]?.click()
    })();
</script>

Django's inbuilt form validation takes care of validating JSON text.

Hackaround (just in case changes doesn't reach code-base)

Define JSONFieldWidget as follow:

"""django_json_widget.widgets.JSONEditorWidget with custom template_name"""

from django_json_widget.widgets import JSONEditorWidget


class JSONFieldWidget(JSONEditorWidget):
    template_name = 'widgets/json_field_widget.html'

Define json_field_widget.html in the templates/widgets folder as follow:

<div {% if not widget.attrs.style %}style="height:{{widget.height|default:'500px'}};width:{{widget.width|default:'90%'}};display:inline-block;"{% endif %}{% include "django/forms/widgets/attrs.html" %}></div>

<textarea id="{{widget.attrs.id}}_textarea" name="{{ widget.name }}" required="" style="display: none">{{ widget.value }}</textarea>

<script>
    (function() {
        const container = document.getElementById("{{ widget.attrs.id }}");
        const textarea = document.getElementById("{{ widget.attrs.id }}_textarea");

        const options = {{ widget.options | safe }};
        options.onChange = function () {
            textarea.value = editor.getText();
        }

        const editor = new JSONEditor(container, options);

        const json = textarea.value;
        editor.setText(json);
        document.getElementById("{{ widget.attrs.id }}").getElementsByClassName('jsoneditor-format')[0]?.click()
    })();
</script>

That is it! Use JSONFieldWidget in place of JSONEditorWidget

JSONEditor library not loaded in form assets

  • django-json-widget version: 1.1.1
  • Django version: 4.1.2
  • Python version: Python 3.10.8
  • Operating System: Fedora 36

Description

Hi all, I pip installed the library and I was trying to use it on my form with a view inherited from django.views.generic.FormView. I've set everything per the documentation but I can not insert data into the JSON field. Taking a glance I saw the error that stated Uncaught ReferenceError: JSONEditor is not defined.

ReferenceError: Can't find variable: JSONEditor

  • django-json-widget version: django-json-widget==0.2.0
  • Django version: Django==2.2.3
  • Python version: Python 3.7.3
  • Operating System: Ubuntu

Added the app in INSTALLED_APPS
Added the widget in the form
If i refresh the admin page, i get

[Error] ReferenceError: Can't find variable: JSONEditor
	(anonymous function) (change:208)
	Global Code (change:211)
[Error] ReferenceError: Can't find variable: JSONEditor
	(anonymous function) (change:231)
	Global Code (change:234)
        var editor = new JSONEditor(container, options);
        var json = {"a": "b"};
        editor.set(json);

allowSchemaSuggestions Not Working

  • django-json-widget version:
  • Django version: 3.2.20
  • Python version: 3.8.10
  • Operating System: Windows

Description

Hey, I was trying to use the allowSchemaSuggestions option from the jsoneditor package. Passed the argument as part of the options of the JSON editor widget, but when the page loads I get the warning:

Unknown option "allowSchemaSuggestions". This option will be ignored

What I Did

This is the configuration for my Widget

        widgets = {
            'configuration': JSONEditorWidget(
                attrs={"style": "width: 100%; border: none; padding: unset;"},
                options={
                    "allowSchemaSuggestions": True,
                    "schema": {
                        "$schema": "http://json-schema.org/draft-07/schema#",
                        "$id": "tag-configuration-schema",
                        "title": "Title",
                        "description": "Description",
                        "type": "object",
                        "additionalProperties": False,
                        "properties": {
                            "type": {
                               "type": "string",
                               "enum": ["access", "trunk"]
                            },
                            "vlan": {
                                "type": "number"
                            },
                            "isolationEnabled": {
                                "type": "boolean"
                            },
                        },
                        "required": []
                    }
                }
            ),
        }

Widget doesn't appear to support "disabled" behavior

  • django-json-widget version: 1.0
  • Django version: 3.0.4
  • Python version: 3.6.10
  • Operating System: Mac

Description

The widget doesn't appear to support the "disabled" html attribute. When I set associated Django field (e.g., JsonField) to disabled, it doesn't render as disabled and still allows the user to make edits in the widget.

If there is a way to render the widget, but in a "disabled" state, I would like to know how to specify that on the widget.

Work around

Set options to restrict mode to read-only text mode and prevent the user from selecting other modes.
Downside: This affects all JSONFields on the form and may not want ALL to be read-only.
formfield_overrides = {
fields.JSONField: {'widget': JSONEditorWidget(options={"mode": "text", "modes": ["text"] })},
}

Save preferred view

  • django-json-widget version: 0.1.0
  • Django version: 1.11
  • Python version: 2.7.12
  • Operating System:

While working with json data I prefer the code view, but I have to change it each time. To address this issue, I suggest saving preferred view in a cookie.

The widget doesn't work with inline

  • django-json-widget version: 0.1.0
  • Django version: 1.9.9
  • Python version: 2.7
  • Operating System: Ubuntu 16:04

Description

Trying to use the widget on a TabularInline, the generated page structure is broken. The "add another record" line gets merged into the widget dom.

Before using the widget:

json-widget-inline-pre

Using the widget:

json-widget-inline-post

What I Did

The attempt was just to use the widget in the formfield_overrides of the inline class, something like:

@admin.register(models.Allocation)
class Allocation(admin.ModelAdmin):

    class AllocationParams(admin.TabularInline):
        formfield_overrides = {
            JSONField: {'widget': JSONEditorWidget},
        }

    inlines = (AllocationParams, )

Multiple JSON fields on one model, last overrides all (!!!)

  • django-json-widget version: 0.1.0
  • Django version: 1.10.1
  • Python version: 2.7
  • Operating System: Mac OS X, Sierra and High Sierra (tested on both)

Description

  • Consider a model with 3 different JSON fields,
  • Set the admin for this model to use this package as explained on the docs,
  • Go to the Django admin interface for this model,
  • The JSONs render OK,
  • Edit the last JSON,
  • Save,
  • The values set for the last of the 3 JSON fields were saved to all 3 JSON fields, overwriting the contents of the other 2.

What I Did

This is a critical issue for us and made us lose some data. We stopped using the library.

Is the maintainer around?

I'm seeing really really old pull requests floating around the repo without any response from the maintainer.

@jmrivas86 hello?

If not, I'm more than willing to fork it and start maintaining it myself. I want to use this in our application but it needs to support Django 2.1, have more flexible styles, etc..

Version 2.0.0 causes issues with Django 4.x due to missing sourcemaps

  • django-json-widget version: 2.0.0
  • Django version: 4.0.10
  • Python version: 3.10
  • Operating System: MacOS

Description

This commit reintroduces //# sourceMappingURL=jsoneditor.map at the end of jsoneditor.min.js which breaks Django 4.x upgrade. This line was previously removed in #70.

What I Did

Tried upgrading to version 2.0.0 to resolve sourcemap issue but collectstatic still fails while using ManifestStaticFilesStorage.

render() error with Django 2.1

  • django-json-widget version: 0.1.1
  • Django version: 2.1
  • Python version: 3.6.5
  • Operating System: Linux

Description

Trying to use the widget in Django 2.1. When using Django 2.0.8 - it works fine. I noticed that froala also had/has this issue-> this may be the cause.

What I Did

Error Occurs: render() got an unexpected keyword argument 'renderer'

Request Method: | GET
-- | --
http://xxxxxxxxxxxxxxxxxxxxxxxxxxx.vfs.cloud9.ap-southeast-1.amazonaws.com/admin/api/inftoken/test_5Fdb59148644095ac4df829c4378125001d3462a6cf4565b54b7d16e90bb/change/
2.1
TypeError
render() got an unexpected keyword argument 'renderer'
/usr/local/lib64/python3.6/site-packages/django/forms/boundfield.py in as_widget, line 93
/usr/bin/python36
3.6.5
['/home/ec2-user/environment/api',  '/usr/lib64/python3.6',  '/usr/lib64/python3.6/lib-dynload',  '/home/ec2-user/.local/lib/python3.6/site-packages',  '/usr/local/lib64/python3.6/site-packages',  '/usr/local/lib/python3.6/site-packages',  '/usr/lib64/python3.6/dist-packages',  '/usr/lib/python3.6/dist-packages']
Sat, 25 Aug 2018 17:38:07 +1000

Trace:

screen

Allow accessing the JSONEditor instance from the outside, e.g. by attaching it to the DOM

  • django-json-widget version: 1.1.1
  • Django version: 2.2
  • Python version: 3.7
  • Operating System: Ubuntu 20.04

What I want to do

I am trying to customize the JSONEditor instance, namely I am trying to disable the Save button on the admin change page whenever invalid JSON is entered.

The jsoneditor comes with a onValidationError hook that would allow me to do this. I cannot configure it on the python side though, as the options dict is serialized. Which you mention:

Options that require functions (eg. onError) are not supported.

I can see the reasoning for this limitation. I would however be nice to be able to get a handle to the widget's JSONEditor instance in a template's script tag, so further customization can be done there.

Right now the editor instance is defined within an IIFE and there is no way to access it later:

(function() {
    ...
    var editor = new JSONEditor(container, options);
})();

The simplest way to be able to fetch that instance from the DOM would be by attaching it to the container as described in a similar ticket on the jsoneditor library itself. This would also support having multiple editors in the same template.

var editor = new JSONEditor(container, options);
container.jsoneditor = editor;

Then on the python-side I could define some attrs that make the container element selectable and just access the editor instance in some overriden admin template there and define custom callbacks etc. to improve the integration of the widget with my page.

Thanks for reading

Python 2.7 compatibility is broken due to the use of super() without any argument

  • django-json-widget version: 0.2.0
  • Django version: 1.11
  • Python version: 2.7
  • Operating System: Debian 4.18.10-2

Description

Hello,

I just run the new 0.2.0 version on my django 1.11 and python2.7 project

Thanks

What I Did

The 0.2.0 version breaks the python2 compatibility because of the use of super() without class and instance arguments.

  File "/usr/local/lib/python2.7/site-packages/django/forms/fields.py", line 228, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/forms/fields.py", line 96, in __init__
    widget = widget()
  File "/usr/local/lib/python2.7/site-packages/django_json_widget/widgets.py", line 20, in __init__
    super().__init__(attrs=attrs)
TypeError: Error when calling the metaclass bases
    super() takes at least 1 argument (0 given)
ERROR: Job failed: exit code 1

Exception while resolving variable 'style' in template 'django_json_widget.html'.

  • django-json-widget version: 1.1.1
  • Django version: 4.0.6
  • Python version: 3.10.5
  • Operating System: Debian

Description

It works but I get an ugly log (DEBUG=True) message because django_json_widget.html template asks {% if not widget.attrs.style %} but style does not exist in attrs.

I defined my form like this:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = (
            "name",
            "config",
        )
        widgets = {
            "config": JSONEditorWidget(width="600px"),
        }

My recommendation is to replace in that template:

<div {% if not widget.attrs.style %}style="height:{{widget.height|default:'500px'}};width:{{widget.width|default:'90%'}};display:inline-block;"{% endif %}{% include "django/forms/widgets/attrs.html" %}></div>

by

<div style="height:{{widget.height|default:'500px'}};width:{{widget.width|default:'90%'}};display:inline-block;"></div>

Allow field validation using JSON schema

Description

I would like to supply a JSON-schema to the widget, and the widget ensures that the field content is validate according to the JSON schema provided.

Change README instructions for django 3.1

  • django-json-widget version:1.0.1
  • Django version: 3.1
  • Python version: 3.8
  • Operating System: linux

Description

JSONField is now a standard field in django models so you can import that from models instead of importing fields from django.contrib.postgres

What I Did

Changed from:

from django.contrib import admin
from django.contrib.postgres import fields
from django_json_widget.widgets import JSONEditorWidget
from .models import YourModel

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        fields.JSONField: {'widget': JSONEditorWidget},
    }

to:

from django.contrib import admin
from django.db import models
from django_json_widget.widgets import JSONEditorWidget
from .models import YourModel

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.JSONField: {'widget': JSONEditorWidget},
    }

Option to preserve ordering as written

  • django-json-widget version: 1.1.1
  • Django version: 3.1.x
  • Python version: 3.9
  • Operating System: Mac, Linux

Description

Expected: Order of object keys is preserved as written

What actually happens: On save, django-json-widget re-orders the keys in the top-level dictionary and in sub-dictionaries arbitrarily. I know that the order of contents of python dictionaries was not guaranteed in the past, but on later versions of python it is, and I am running a version of python that should preserve dictionary ordering. Oh, but this is JSON, not Python, and I see that JSON objects still do not guarantee ordering.

Is there any way to prevent this for some models where it's undesirable? In my use case, I'm rendering Swagger (OAS) docs with Redoc and I want to control the order of endpoints listed in the UI. Redoc says "We preserve the order in which they're presented" but I can't control that because this widget re-orders them on save.

Source map line in jsoneditor.min.js makes collectstatic fail

  • django-json-widget version: 1.1.1
  • Django version: 4.0
  • Python version: 3.8.10
  • Operating System: linux ubuntu (in docker)

Description

When running python manage.py collectstatic with whitenoise 5.3.0, I get the following error:

es/management/commands/collectstatic.py", line 134, in collect
remote:            raise processed
remote:        whitenoise.storage.MissingFileError: The file 'dist/jsoneditor.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f260dc431f0>.
remote:        The JS file 'dist/jsoneditor.min.js' references a file which could not be found:
remote:          dist/jsoneditor.map

it seems it's because of the source map bit. When we removed the last line https://github.com/jmrivas86/django-json-widget/blob/master/django_json_widget/static/dist/jsoneditor.min.js#L46 , it works.

Easier integration with CSP

  • django-json-widget version: master branch (32c6acf
  • Django version: 4.2
  • Python version: 3.11
  • Operating System: Linux/OSX

Description

Our site requires a Content Security Policy and uses django-csp to implement this. One restriction is that inline scripts must have a nonce. Since this library makes use of an inline script to wire up JSONEditor to the form fields in the Widget, we are unable to use the library as is.

What I Did

Since request is not available to the context of a Widget, my first attempt to fix was by extending the provided Widget and adding nonce to a custom template. Ultimately, I was able to work around by providing a separate script that lives at the page level. I'll be happy to put together a PR to fix if interested in this more generally.

Using StaticFilesStorage

  • django-json-widget version: 0.2.0

Description

Im using StaticFilesStorage to serve static files over s3. Is there a way to do this?

Widget does not work in inlines with grappelli admin

  • django-json-widget version: 1.1.1
  • Django version: 3.2
  • Python version: 3.10
  • Operating System: linux

Description

Widget is not editable when used in inlines with grappelli installed

In tablular inlines:
image

In stacked inlines:
image

Django Collect static fail

I found an issue.
I do not know why, but after I add this library, I failed release new version because of failure of collect static.

Could you please check this issue?
Thanks

Is module ready to use with Django 2.0?

  • django-json-widget version: latest
  • Django version: 2.0
  • Python version: 3.6.3
  • Operating System: Debian 9.2

Description

Hello! Is package ready to use with Django 2.0?

Static files best practice.

  • django-json-widget version: 1.1.1
  • Django version: 4.1.7
  • Python version: 3.11
  • Operating System: Ubuntu

Description

Static files should be moved to a django_json_widget/ parent directory to avoid possible collisions with other app's static files.

What I Did

As you can see the other apps static files are contained in a directory named like the app they blong to (the dist directory belong to django-json-widget):

Screenshot 2023-03-29 at 17 46 49

Custom width height in config Form

  • django-json-widget version: 0.2.0
  • Django version: 1.11
  • Python version: 3.4.5
  • Operating System: ubuntu 18.10

Description

How to use custom width and height in form django admin with key
JSONEditorWidget() . I cant found any example like this. I see configuration said :

width: Width of the editor as a string with CSS size units (px, em, % etc). Defaults to 90%.
height: Height of the editor as a string CSS size units. Defaults to 550px.

What I Did

My config work perfect, without it look so big

class ServiceForm(forms.ModelForm):
    class Meta:
        model = Service
        widgets = {
            'test': JSONEditorWidget(),
        }

i try JSONEditorWidget(with="50") But editor not accept this param

My pip list show version is 0.2.0. But in your project, file widgets.py have more param than my version pip downloaded. It maybe this problem.
thanks

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.