Return a ModelForm as JsonResponse? serialization issue.

Hi everyone, I am currently working with an UpdateView and I am having trouble rendering a ModelForm as Json, with a get request.

class CompanyUpdateView(UpdateView):

    """View for updating company details"""

    model = Company
    form_class = CompanyForm

    def get_form(self, form_class=None):
        form_class = CompanyForm(initial=self.get_object())
        logger.debug(f'form class: {form_class}')
        return JsonResponse(form_class, safe=False)

    def form_valid(self, form):
        self.object = form.save()
        return JsonResponse({'message': 'company updated successfully.'}, 
                             status=200)

I’m running into the error Object of type CompanyForm is not JSON serializable

Also, the line… logger.debug(f'form class: {form_class}') in the get_form method prints out the form class and instance as an html table. So I do know that it is grabbing the instance, and the form. Just having trouble serializing the actual form to display it as Json.

Is this something that even needs to be serialized in a json format in order to bring up the form on the front end as an Ajax request?

Any help is greatly appreciated!

See the Serialization topic page, section on JSON. Basically, the built-in serializer doesn’t handle nested class structures. You can either build something similar to what’s described on that page, or if your needs are more extensive, you can install the Django Rest Framework package and use the serializers that it contains.