Thanks to the friendly and detailed advice of @LB from Wagtail community (https://wagtail.io/slack/)
views.py
class FormSubmissionViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
"""
A viewset for viewing and editing contact form submissions.
"""
serializer_class = FormSubmissionSerializer
def create(self, request, *args, **kwargs):
try:
page = Page.objects.get(id=self.kwargs.get("id")).specific
form = page.get_form(
request.data, request.FILES, page=page, user=request.user
) # use request.data instead of request.POST to handle raw json
if form.is_valid():
page.process_form_submission(form)
headers = self.get_success_headers(form.cleaned_data)
return Response(
form.cleaned_data, status=status.HTTP_201_CREATED, headers=headers
)
return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)
except Page.DoesNotExist:
return Response({"success": False}, status=status.HTTP_400_BAD_REQUEST)
def get_queryset(self):
try:
page = Page.objects.get(id=self.kwargs.get("id"))
queryset = FormSubmission.objects.filter(page=page)
except Page.DoesNotExist:
queryset = FormSubmission.objects.none()
return queryset
serializers.py
class FormSubmissionSerializer(serializers.ModelSerializer):
class Meta:
model = FormSubmission
fields = "__all__"
api.py
router = routers.DefaultRouter()
router.register(r"form/(?P<id>\d+)/submissions", FormSubmissionViewSet, basename="form-submission")