Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jean-Zombie/52c0fea84b8a0e0ba60f489670034183 to your computer and use it in GitHub Desktop.
Save Jean-Zombie/52c0fea84b8a0e0ba60f489670034183 to your computer and use it in GitHub Desktop.
create submissions to wagtail forms created with formbuilder, with django rest framework

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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment