Skip to content

Resolve #159 -- Add custom JSONEncoder support via setting #160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 30, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions django_select2/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@ class Select2Conf(AppConf):
``settings.DJANGO_SELECT2_I18N`` refers to :attr:`.I18N_PATH`.
"""

"""
Custo JSON encoder class used for encoding JSON response used in ModelSelect2Widget, ModelSelect2MultipleWidget
and ModelSelect2TagWidget.
Useful when your models uses some special proxy fields and
you get error: Object of type <field> is not JSON serializable

Default value is: django.core.serializers.json.DjangoJSONEncoder

For example:

If you use django-hashid-field package, you'll get an Object of type Hashid is not JSON serializable when you try
to use ModelSelect2Widget.
Just extend DjangoJSONEncoder:
from django.core.serializers.json import DjangoJSONEncoder
from hashid_field import Hashid

class HashidJSONEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, Hashid):
return str(o)
return super().default(o)

And set SELECT2_JSON_ENCODER to 'app_name.econders.HashidJSONEncoder' in settings.py of your project.
"""
JSON_ENCODER = 'django.core.serializers.json.DjangoJSONEncoder'

class Meta:
"""Prefix for all Django-Select2 settings."""

Expand Down
4 changes: 3 additions & 1 deletion django_select2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.core.signing import BadSignature
from django.http import Http404, JsonResponse
from django.views.generic.list import BaseListView
from django.utils.module_loading import import_string

from .cache import cache
from .conf import settings
Expand Down Expand Up @@ -43,7 +44,8 @@ def get(self, request, *args, **kwargs):
for obj in context["object_list"]
],
"more": context["page_obj"].has_next(),
}
},
encoder=import_string(settings.SELECT2_JSON_ENCODER)
)

def get_queryset(self):
Expand Down