Skip to content
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

TypeError: Object of type datetime is not JSON serializable #174

Open
Alexeino opened this issue Jan 9, 2025 · 3 comments
Open

TypeError: Object of type datetime is not JSON serializable #174

Alexeino opened this issue Jan 9, 2025 · 3 comments

Comments

@Alexeino
Copy link

Alexeino commented Jan 9, 2025

If the message contains the datetime.datetime fields it isn't able to load message in django admin task detail view. Results into TypeError.
I had to override the TaskAdmin.message_details to do something like this
json.dumps(instance.message._asdict(), indent=4, cls=DjangoJSONEncoder) # Using DjangoJSONEncoder here
and unregister and register with this CustomTaskAdmin.

Any other ways to mitigate it ?

@andrewgy8
Copy link
Collaborator

andrewgy8 commented Jan 10, 2025

Hey @Alexeino !

Are you using a custom encoder? Any details on how you are calling the send method?

Im unable to reproduce this, as dramatiq expectedly throws an error when passing a datetime object like datetime.now() to send.

@Alexeino
Copy link
Author

Actually Issue arises, when django_dramatiq.admin.TaskAdmin tries to produce message_details
image
which is then displayed in task details in django admin details view. It actually is a display error where it is not able to convert instance.message if this message has a datetime.datetime type of field.
So when somebody accesses a Task detail in django admin url like /system/admin/django_dramatiq/task/8rthr4502-c715-4a96-b41f-b77c75hggc12e/change/ , raises TypeError: Object of type datetime is not JSON serializable.
So to mitigate it I had to dome something like this.

admin.site.unregister(Task)

@admin.register(Task)
class CustomTaskAdmin(TaskAdmin):
    def message_details(self, instance):
        """
        Overriding TaskAdmin from django_dramatiq to avoid Serialization Errors for datetime objects.
        In future if fixed by library, this can be removed.
        """
        message_details = json.dumps(instance.message._asdict(), indent=4, cls=DjangoJSONEncoder)  # noqa: SLF001
        return mark_safe("<pre>%s</pre>" % message_details)

So here I am providing DjangoJSONEncoder which fixes it.
Not sure if it's best option but it wokred for me

@andrewgy8
Copy link
Collaborator

Which version of django_dramatiq are you running?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants