5

I am pretty new to Django rest-framework and trying to render a simple JSON view not based on the model. I could not figure out how to do this since all of the examples involves rendering JSON from the Model classes. Below is the simple example what I was trying to do.

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

class Comment(object):
    def __init__(self, email, content, created=None):
        self.email = email
        self.content = content
        self.created = created or datetime.now()

def comment_view(request):
    comment = Comment(email='[email protected]', content='foo bar')
    serializer = CommentSerializer(comment)
    json = JSONRenderer().render(serializer.data)
    return json
0

1 Answer 1

13

You can use it like here:

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view()
def comment_view(request):
    comment = Comment(email='[email protected]', content='foo bar')
    serializer = CommentSerializer(comment)
    return Response(serializer.data)

Finally don't forget to put it in the urls.py:

urlpatterns = [
    path('comments/', comment_view, name='comment-view'),
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.