Skip to content

Instantly share code, notes, and snippets.

@dannvix
Last active March 31, 2022 06:44
Show Gist options
  • Save dannvix/29f53570dfde13f29c35 to your computer and use it in GitHub Desktop.
Save dannvix/29f53570dfde13f29c35 to your computer and use it in GitHub Desktop.
Custom Django JsonResponse which supports datetime.datetime serialization
# project/forum/views.py
import json
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.forms.models import model_to_dict
from forum.models import Post
class DateTimeEncoder(json.JSONEncoder):
# default JSONEncoder cannot serialize datetime.datetime objects
def default(self, obj):
if isinstance(obj, datetime):
encoded_object = obj.strftime('%s')
else:
encoded_object = super(self, obj)
return encoded_object
class JsonResponse(HttpResponse):
def __init__(self, content, mimetype='application/json', status=None, content_type='application/json'):
json_text = json.dumps(content, cls=DateTimeEncoder)
super(JsonResponse, self).__init__(
content=json_text,
status=status,
content_type=content_type)
# GET /posts/123/comments/456.json
# => {"id": 456, "content": "...", "user_id": 9, "post": {"id": "123", "title": "...", "content": "..."} }
def posts_comments_item_json(request, post_id, comment_id):
post = get_object_or_404(Post, pk=post_id)
comment = post.comment_set.get(pk=comment_id)
result = model_to_dict(comment).copy()
result.update(dict(post=model_to_dict(post)))
return JsonResponse(result)
@LennyLip
Copy link

LennyLip commented Mar 31, 2022

from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder

class DateTimeEncoder(DjangoJSONEncoder):
    pass

view:
return JsonResponse(result, encoder=DateTimeEncoder)

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