I used Wagtail's contributed Form builder module to create a simple Contacts form in Wagtail Admin. The form has the dynamically added fields Name, Email, Subject and Message; the model ContactPage
inherits from AbstractForm
.
The problem:
I would like to use the entered name in the Name field to personalize the response message to the user who used the contact form. Wagtail's Read The Docs page on Form builder only states that form
is part of the context for the form_page.html template, while the form_page_landing.html template is a standard template. Is it possible to access the form-submitted values through the context of the landing template out of the box somehow? If not, could anyone give an example how/what page function to override, in order to add the information I need to the context? Thanks!
Wagtail serves its forms pages through AbstractForm
(https://github.com/wagtail/wagtail/blob/master/wagtail/contrib/forms/models.py#L296) and specifically its serve
method. This method checks to see if the HTTP method is 'POST' so it either processes the form and returns the landing page or it renders the actual form. You can override this method to your custom form class so it updates the context of the landing page, something like this:
def serve(self, request, *args, **kwargs): if request.method == 'POST': form = self.get_form(request.POST, page=self, user=request.user) if form.is_valid(): self.process_form_submission(form) # Update the original landing page context with other data landing_page_context = self.get_context(request) landing_page_context['name'] = form.cleaned_data['name'] return render( request, self.get_landing_page_template(request), landing_page_context ) else: form = self.get_form(page=self, user=request.user) context = self.get_context(request) context['form'] = form return render( request, self.get_template(request), context )
Now the landing page context will have a name
context variable containing the value of the name form field!