Skip to content

Add custom JSON encoder #159

Closed
Closed
@N1K1TAS95

Description

@N1K1TAS95

Hi there!
I was wondering if it's possibile to add some kind of option to specify a custom JSON encoder in AutoResponseView view.
I'm using this package https://github.com/nshafer/django-hashid-field and if I don't specify the specific JSON encoder while I'm using ModelSelect2Widget widget, it will throw an Object of type Hashid is not JSON serializable error.

Here the AutoResponseView that works:

from django.core import signing
from django.core.signing import BadSignature
from django.core.serializers.json import DjangoJSONEncoder
from django.http import Http404, JsonResponse
from django.views.generic.list import BaseListView
from hashid_field.hashid import Hashid # from the package [https://github.com/nshafer/django-hashid-field](https://github.com/nshafer/django-hashid-field)

from .cache import cache
from .conf import settings

# custom JSON encoder
class HashidJSONEncoder(DjangoJSONEncoder):

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


class AutoResponseView(BaseListView):

    def get(self, request, *args, **kwargs):
        self.widget = self.get_widget_or_404()
        self.term = kwargs.get("term", request.GET.get("term", ""))
        self.object_list = self.get_queryset()
        context = self.get_context_data()
        return JsonResponse(
            {
                "results": [
                    {"text": self.widget.label_from_instance(obj), "id": obj.pk}
                    for obj in context["object_list"]
                ],
                "more": context["page_obj"].has_next(),
            },
            encoder=HashidJSONEncoder # using custom JSON encoder
        )

Thanks a lot!

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions