Ben
Ben

Reputation: 177

How to make a FormSet JSON serializable?

I am trying to pass a formset as JSON data but i am getting Object of type HabitFormFormSet is not JSON serializable.

Why is that ?

my view:

def modal_view(request):
    HabitFormSet = modelformset_factory(
        Habit, extra=0, form=HabitModelForm)
    formset = HabitFormSet(
        request.POST,
        queryset=Habit.objects.filter(user=request.user),
    )
    if formset.is_valid():
        formset.save()
        data = {"formset": formset}
        return JsonResponse(data)

    return HttpResponseRedirect(reverse('home'))

If I use a list of dictionaries i get Object of type Habit is not JSON serializable:

    if formset.is_valid():
        formset.save()
        formlist = list()
        for form in formset:
            formlist.append(form.cleaned_data)
        data = {"formlist": formlist}
        return JsonResponse(data)

Upvotes: 0

Views: 505

Answers (2)

AKX
AKX

Reputation: 169051

There's no default JSON serialization for custom classes.

You may want to add a, say, to_json() or as_json() (choose one) function to your Habit model, e.g.

def to_json(self):
    return {
        "id": self.id,
        "something": self.something,
    }

Then, make a list of the (newly saved) Habits:

data = {"new_habits": [form.instance.to_json() for form in formset if form.instance.id]}
return JsonResponse(data)

Upvotes: 2

Timothé Delion
Timothé Delion

Reputation: 1460

The built-it JSONEncoder has a strategy to serialize each python primitive type, but he does not know how to serialize your custom types (especially instances of your custom classes).

You might write your own JSONEncoder subclass, and tell JsonResponse to use it

Upvotes: 1

Related Questions