'Why does Django REST have serializers, can't forms perform the same function?

I am working through the Django REST tutorial, and I don't see the benefit of serializers, I feel like I must be missing something:

Client Side

Django REST is for Ajax calls. On the client side, if one would like a JSON version of a Form, one can perform:

    const FORM = document.querySelect('form');
    const formData = new FormData(FORM);
     const init = {
        body: formData,
        method: "post",
     };
     const response = await fetch(url, init);

This is the JSON version of the form that can be fetch POST'ed via AJAX to Django REST.

Server Side

Say I have a dictionary of values, and I wish to check one can make a valid object from it:

# Forms
FormClass(data=data).is_valid()
# Serializer
Serializer(data=data).is_valid()

Say I have a dictionary of posted values, and I wish to create an object from them

# Forms
FormClass(data=data).save()
# Serializer
Serializer(data=data).save()

Say I have a form/serializer instance, and I wish to have a JSON representation:

# Forms
json.dumps(form.data)
# Serializer
json.dumps(serializer.data)

I can give similar examples as above for update/delete operations.

For the view, we don't need serializers again:

from rest_framework.views import APIView

class FooView(APIView):
    def post(self, request, **kwargs):
        form = FooForm(request.data)
        if form.is_valid():
            form.save()

As shown above, one can use forms to perform these actions, with the added benefit of they can be rendered in templates, so why use Serializers over forms?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source