customisation.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. Form builder customisation
  2. ==========================
  3. For a basic usage example see :ref:`form_builder_usage`.
  4. Custom ``related_name`` for form fields
  5. ---------------------------------------
  6. If you want to change ``related_name`` for form fields
  7. (by default ``AbstractForm`` and ``AbstractEmailForm`` expect ``form_fields`` to be defined),
  8. you will need to override the ``get_form_fields`` method.
  9. You can do this as shown below.
  10. .. code-block:: python
  11. from modelcluster.fields import ParentalKey
  12. from wagtail.admin.edit_handlers import (
  13. FieldPanel, FieldRowPanel,
  14. InlinePanel, MultiFieldPanel
  15. )
  16. from wagtail.core.fields import RichTextField
  17. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
  18. class FormField(AbstractFormField):
  19. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='custom_form_fields')
  20. class FormPage(AbstractEmailForm):
  21. intro = RichTextField(blank=True)
  22. thank_you_text = RichTextField(blank=True)
  23. content_panels = AbstractEmailForm.content_panels + [
  24. FieldPanel('intro', classname="full"),
  25. InlinePanel('custom_form_fields', label="Form fields"),
  26. FieldPanel('thank_you_text', classname="full"),
  27. MultiFieldPanel([
  28. FieldRowPanel([
  29. FieldPanel('from_address', classname="col6"),
  30. FieldPanel('to_address', classname="col6"),
  31. ]),
  32. FieldPanel('subject'),
  33. ], "Email"),
  34. ]
  35. def get_form_fields(self):
  36. return self.custom_form_fields.all()
  37. Custom form submission model
  38. ----------------------------
  39. If you need to save additional data, you can use a custom form submission model.
  40. To do this, you need to:
  41. * Define a model that extends ``wagtail.contrib.forms.models.AbstractFormSubmission``.
  42. * Override the ``get_submission_class`` and ``process_form_submission`` methods in your page model.
  43. Example:
  44. .. code-block:: python
  45. import json
  46. from django.conf import settings
  47. from django.core.serializers.json import DjangoJSONEncoder
  48. from django.db import models
  49. from modelcluster.fields import ParentalKey
  50. from wagtail.admin.edit_handlers import (
  51. FieldPanel, FieldRowPanel,
  52. InlinePanel, MultiFieldPanel
  53. )
  54. from wagtail.core.fields import RichTextField
  55. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
  56. class FormField(AbstractFormField):
  57. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
  58. class FormPage(AbstractEmailForm):
  59. intro = RichTextField(blank=True)
  60. thank_you_text = RichTextField(blank=True)
  61. content_panels = AbstractEmailForm.content_panels + [
  62. FieldPanel('intro', classname="full"),
  63. InlinePanel('form_fields', label="Form fields"),
  64. FieldPanel('thank_you_text', classname="full"),
  65. MultiFieldPanel([
  66. FieldRowPanel([
  67. FieldPanel('from_address', classname="col6"),
  68. FieldPanel('to_address', classname="col6"),
  69. ]),
  70. FieldPanel('subject'),
  71. ], "Email"),
  72. ]
  73. def get_submission_class(self):
  74. return CustomFormSubmission
  75. def process_form_submission(self, form):
  76. self.get_submission_class().objects.create(
  77. form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
  78. page=self, user=form.user
  79. )
  80. class CustomFormSubmission(AbstractFormSubmission):
  81. user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
  82. Add custom data to CSV export
  83. -----------------------------
  84. If you want to add custom data to the CSV export, you will need to:
  85. * Override the ``get_data_fields`` method in page model.
  86. * Override ``get_data`` in the submission model.
  87. The following example shows how to add a username to the CSV export:
  88. .. code-block:: python
  89. import json
  90. from django.conf import settings
  91. from django.core.serializers.json import DjangoJSONEncoder
  92. from django.db import models
  93. from modelcluster.fields import ParentalKey
  94. from wagtail.admin.edit_handlers import (
  95. FieldPanel, FieldRowPanel,
  96. InlinePanel, MultiFieldPanel
  97. )
  98. from wagtail.core.fields import RichTextField
  99. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
  100. class FormField(AbstractFormField):
  101. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
  102. class FormPage(AbstractEmailForm):
  103. intro = RichTextField(blank=True)
  104. thank_you_text = RichTextField(blank=True)
  105. content_panels = AbstractEmailForm.content_panels + [
  106. FieldPanel('intro', classname="full"),
  107. InlinePanel('form_fields', label="Form fields"),
  108. FieldPanel('thank_you_text', classname="full"),
  109. MultiFieldPanel([
  110. FieldRowPanel([
  111. FieldPanel('from_address', classname="col6"),
  112. FieldPanel('to_address', classname="col6"),
  113. ]),
  114. FieldPanel('subject'),
  115. ], "Email"),
  116. ]
  117. def get_data_fields(self):
  118. data_fields = [
  119. ('username', 'Username'),
  120. ]
  121. data_fields += super().get_data_fields()
  122. return data_fields
  123. def get_submission_class(self):
  124. return CustomFormSubmission
  125. def process_form_submission(self, form):
  126. self.get_submission_class().objects.create(
  127. form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
  128. page=self, user=form.user
  129. )
  130. class CustomFormSubmission(AbstractFormSubmission):
  131. user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
  132. def get_data(self):
  133. form_data = super().get_data()
  134. form_data.update({
  135. 'username': self.user.username,
  136. })
  137. return form_data
  138. Note that this code also changes the submissions list view.
  139. Check that a submission already exists for a user
  140. -------------------------------------------------
  141. If you want to prevent users from filling in a form more than once,
  142. you need to override the ``serve`` method in your page model.
  143. Example:
  144. .. code-block:: python
  145. import json
  146. from django.conf import settings
  147. from django.core.serializers.json import DjangoJSONEncoder
  148. from django.db import models
  149. from django.shortcuts import render
  150. from modelcluster.fields import ParentalKey
  151. from wagtail.admin.edit_handlers import (
  152. FieldPanel, FieldRowPanel,
  153. InlinePanel, MultiFieldPanel
  154. )
  155. from wagtail.core.fields import RichTextField
  156. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
  157. class FormField(AbstractFormField):
  158. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
  159. class FormPage(AbstractEmailForm):
  160. intro = RichTextField(blank=True)
  161. thank_you_text = RichTextField(blank=True)
  162. content_panels = AbstractEmailForm.content_panels + [
  163. FieldPanel('intro', classname="full"),
  164. InlinePanel('form_fields', label="Form fields"),
  165. FieldPanel('thank_you_text', classname="full"),
  166. MultiFieldPanel([
  167. FieldRowPanel([
  168. FieldPanel('from_address', classname="col6"),
  169. FieldPanel('to_address', classname="col6"),
  170. ]),
  171. FieldPanel('subject'),
  172. ], "Email"),
  173. ]
  174. def serve(self, request, *args, **kwargs):
  175. if self.get_submission_class().objects.filter(page=self, user__pk=request.user.pk).exists():
  176. return render(
  177. request,
  178. self.template,
  179. self.get_context(request)
  180. )
  181. return super().serve(request, *args, **kwargs)
  182. def get_submission_class(self):
  183. return CustomFormSubmission
  184. def process_form_submission(self, form):
  185. self.get_submission_class().objects.create(
  186. form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
  187. page=self, user=form.user
  188. )
  189. class CustomFormSubmission(AbstractFormSubmission):
  190. user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
  191. class Meta:
  192. unique_together = ('page', 'user')
  193. Your template should look like this:
  194. .. code-block:: django
  195. {% load wagtailcore_tags %}
  196. <html>
  197. <head>
  198. <title>{{ page.title }}</title>
  199. </head>
  200. <body>
  201. <h1>{{ page.title }}</h1>
  202. {% if user.is_authenticated and user.is_active or request.is_preview %}
  203. {% if form %}
  204. <div>{{ page.intro|richtext }}</div>
  205. <form action="{% pageurl page %}" method="POST">
  206. {% csrf_token %}
  207. {{ form.as_p }}
  208. <input type="submit">
  209. </form>
  210. {% else %}
  211. <div>You can fill in the from only one time.</div>
  212. {% endif %}
  213. {% else %}
  214. <div>To fill in the form, you must to log in.</div>
  215. {% endif %}
  216. </body>
  217. </html>
  218. Multi-step form
  219. ---------------
  220. The following example shows how to create a multi-step form.
  221. .. code-block:: python
  222. from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
  223. from django.shortcuts import render
  224. from modelcluster.fields import ParentalKey
  225. from wagtail.admin.edit_handlers import (
  226. FieldPanel, FieldRowPanel,
  227. InlinePanel, MultiFieldPanel
  228. )
  229. from wagtail.core.fields import RichTextField
  230. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
  231. class FormField(AbstractFormField):
  232. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
  233. class FormPage(AbstractEmailForm):
  234. intro = RichTextField(blank=True)
  235. thank_you_text = RichTextField(blank=True)
  236. content_panels = AbstractEmailForm.content_panels + [
  237. FieldPanel('intro', classname="full"),
  238. InlinePanel('form_fields', label="Form fields"),
  239. FieldPanel('thank_you_text', classname="full"),
  240. MultiFieldPanel([
  241. FieldRowPanel([
  242. FieldPanel('from_address', classname="col6"),
  243. FieldPanel('to_address', classname="col6"),
  244. ]),
  245. FieldPanel('subject'),
  246. ], "Email"),
  247. ]
  248. def get_form_class_for_step(self, step):
  249. return self.form_builder(step.object_list).get_form_class()
  250. def serve(self, request, *args, **kwargs):
  251. """
  252. Implements a simple multi-step form.
  253. Stores each step into a session.
  254. When the last step was submitted correctly, saves whole form into a DB.
  255. """
  256. session_key_data = 'form_data-%s' % self.pk
  257. is_last_step = False
  258. step_number = request.GET.get('p', 1)
  259. paginator = Paginator(self.get_form_fields(), per_page=1)
  260. try:
  261. step = paginator.page(step_number)
  262. except PageNotAnInteger:
  263. step = paginator.page(1)
  264. except EmptyPage:
  265. step = paginator.page(paginator.num_pages)
  266. is_last_step = True
  267. if request.method == 'POST':
  268. # The first step will be submitted with step_number == 2,
  269. # so we need to get a form from previous step
  270. # Edge case - submission of the last step
  271. prev_step = step if is_last_step else paginator.page(step.previous_page_number())
  272. # Create a form only for submitted step
  273. prev_form_class = self.get_form_class_for_step(prev_step)
  274. prev_form = prev_form_class(request.POST, page=self, user=request.user)
  275. if prev_form.is_valid():
  276. # If data for step is valid, update the session
  277. form_data = request.session.get(session_key_data, {})
  278. form_data.update(prev_form.cleaned_data)
  279. request.session[session_key_data] = form_data
  280. if prev_step.has_next():
  281. # Create a new form for a following step, if the following step is present
  282. form_class = self.get_form_class_for_step(step)
  283. form = form_class(page=self, user=request.user)
  284. else:
  285. # If there is no next step, create form for all fields
  286. form = self.get_form(
  287. request.session[session_key_data],
  288. page=self, user=request.user
  289. )
  290. if form.is_valid():
  291. # Perform validation again for whole form.
  292. # After successful validation, save data into DB,
  293. # and remove from the session.
  294. form_submission = self.process_form_submission(form)
  295. del request.session[session_key_data]
  296. # render the landing page
  297. return self.render_landing_page(request, form_submission, *args, **kwargs)
  298. else:
  299. # If data for step is invalid
  300. # we will need to display form again with errors,
  301. # so restore previous state.
  302. form = prev_form
  303. step = prev_step
  304. else:
  305. # Create empty form for non-POST requests
  306. form_class = self.get_form_class_for_step(step)
  307. form = form_class(page=self, user=request.user)
  308. context = self.get_context(request)
  309. context['form'] = form
  310. context['fields_step'] = step
  311. return render(
  312. request,
  313. self.template,
  314. context
  315. )
  316. Your template for this form page should look like this:
  317. .. code-block:: django
  318. {% load wagtailcore_tags %}
  319. <html>
  320. <head>
  321. <title>{{ page.title }}</title>
  322. </head>
  323. <body>
  324. <h1>{{ page.title }}</h1>
  325. <div>{{ page.intro|richtext }}</div>
  326. <form action="{% pageurl page %}?p={{ fields_step.number|add:"1" }}" method="POST">
  327. {% csrf_token %}
  328. {{ form.as_p }}
  329. <input type="submit">
  330. </form>
  331. </body>
  332. </html>
  333. Note that the example shown before allows the user to return to a previous step,
  334. or to open a second step without submitting the first step.
  335. Depending on your requirements, you may need to add extra checks.
  336. Show results
  337. ------------
  338. If you are implementing polls or surveys, you may want to show results after submission.
  339. The following example demonstrates how to do this.
  340. First, you need to collect results as shown below:
  341. .. code-block:: python
  342. from modelcluster.fields import ParentalKey
  343. from wagtail.admin.edit_handlers import (
  344. FieldPanel, FieldRowPanel,
  345. InlinePanel, MultiFieldPanel
  346. )
  347. from wagtail.core.fields import RichTextField
  348. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
  349. class FormField(AbstractFormField):
  350. page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
  351. class FormPage(AbstractEmailForm):
  352. intro = RichTextField(blank=True)
  353. thank_you_text = RichTextField(blank=True)
  354. content_panels = AbstractEmailForm.content_panels + [
  355. FieldPanel('intro', classname="full"),
  356. InlinePanel('form_fields', label="Form fields"),
  357. FieldPanel('thank_you_text', classname="full"),
  358. MultiFieldPanel([
  359. FieldRowPanel([
  360. FieldPanel('from_address', classname="col6"),
  361. FieldPanel('to_address', classname="col6"),
  362. ]),
  363. FieldPanel('subject'),
  364. ], "Email"),
  365. ]
  366. def get_context(self, request, *args, **kwargs):
  367. context = super().get_context(request, *args, **kwargs)
  368. # If you need to show results only on landing page,
  369. # you may need check request.method
  370. results = dict()
  371. # Get information about form fields
  372. data_fields = [
  373. (field.clean_name, field.label)
  374. for field in self.get_form_fields()
  375. ]
  376. # Get all submissions for current page
  377. submissions = self.get_submission_class().objects.filter(page=self)
  378. for submission in submissions:
  379. data = submission.get_data()
  380. # Count results for each question
  381. for name, label in data_fields:
  382. answer = data.get(name)
  383. if answer is None:
  384. # Something wrong with data.
  385. # Probably you have changed questions
  386. # and now we are receiving answers for old questions.
  387. # Just skip them.
  388. continue
  389. if type(answer) is list:
  390. # Answer is a list if the field type is 'Checkboxes'
  391. answer = u', '.join(answer)
  392. question_stats = results.get(label, {})
  393. question_stats[answer] = question_stats.get(answer, 0) + 1
  394. results[label] = question_stats
  395. context.update({
  396. 'results': results,
  397. })
  398. return context
  399. Next, you need to transform your template to display the results:
  400. .. code-block:: django
  401. {% load wagtailcore_tags %}
  402. <html>
  403. <head>
  404. <title>{{ page.title }}</title>
  405. </head>
  406. <body>
  407. <h1>{{ page.title }}</h1>
  408. <h2>Results</h2>
  409. {% for question, answers in results.items %}
  410. <h3>{{ question }}</h3>
  411. {% for answer, count in answers.items %}
  412. <div>{{ answer }}: {{ count }}</div>
  413. {% endfor %}
  414. {% endfor %}
  415. <div>{{ page.intro|richtext }}</div>
  416. <form action="{% pageurl page %}" method="POST">
  417. {% csrf_token %}
  418. {{ form.as_p }}
  419. <input type="submit">
  420. </form>
  421. </body>
  422. </html>
  423. You can also show the results on the landing page.
  424. Custom landing page redirect
  425. ----------------------------
  426. You can override the ``render_landing_page`` method on your `FormPage` to change what is rendered when a form submits.
  427. In this example below we have added a `thank_you_page` field that enables custom redirects after a form submits to the selected page.
  428. When overriding the ``render_landing_page`` method, we check if there is a linked `thank_you_page` and then redirect to it if it exists.
  429. Finally, we add a URL param of `id` based on the ``form_submission`` if it exists.
  430. .. code-block:: python
  431. from django.shortcuts import redirect
  432. from wagtail.admin.edit_handlers import FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel
  433. from wagtail.contrib.forms.models import AbstractEmailForm
  434. class FormPage(AbstractEmailForm):
  435. # intro, thank_you_text, ...
  436. thank_you_page = models.ForeignKey(
  437. 'wagtailcore.Page',
  438. null=True,
  439. blank=True,
  440. on_delete=models.SET_NULL,
  441. related_name='+',
  442. )
  443. def render_landing_page(self, request, form_submission=None, *args, **kwargs):
  444. if self.thank_you_page:
  445. url = self.thank_you_page.url
  446. # if a form_submission instance is available, append the id to URL
  447. # when previewing landing page, there will not be a form_submission instance
  448. if form_submission:
  449. url += '?id=%s' % form_submission.id
  450. return redirect(url, permanent=False)
  451. # if no thank_you_page is set, render default landing page
  452. return super().render_landing_page(request, form_submission, *args, **kwargs)
  453. content_panels = AbstractEmailForm.content_panels + [
  454. FieldPanel('intro', classname='full'),
  455. InlinePanel('form_fields'),
  456. FieldPanel('thank_you_text', classname='full'),
  457. FieldPanel('thank_you_page'),
  458. MultiFieldPanel([
  459. FieldRowPanel([
  460. FieldPanel('from_address', classname='col6'),
  461. FieldPanel('to_address', classname='col6'),
  462. ]),
  463. FieldPanel('subject'),
  464. ], 'Email'),
  465. ]
  466. Customise form submissions listing in Wagtail Admin
  467. ---------------------------------------------------
  468. The Admin listing of form submissions can be customised by setting the attribute ``submissions_list_view_class`` on your FormPage model.
  469. The list view class must be a subclass of ``SubmissionsListView`` from ``wagtail.contrib.forms.views``, which is a child class of Django's class based :class:`~django.views.generic.list.ListView`.
  470. Example:
  471. .. code-block:: python
  472. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
  473. from wagtail.contrib.forms.views import SubmissionsListView
  474. class CustomSubmissionsListView(SubmissionsListView):
  475. paginate_by = 50 # show more submissions per page, default is 20
  476. ordering = ('submit_time',) # order submissions by oldest first, normally newest first
  477. ordering_csv = ('-submit_time',) # order csv export by newest first, normally oldest first
  478. # override the method to generate csv filename
  479. def get_csv_filename(self):
  480. """ Returns the filename for CSV file with page slug at start"""
  481. filename = super().get_csv_filename()
  482. return self.form_page.slug + '-' + filename
  483. class FormField(AbstractFormField):
  484. page = ParentalKey('FormPage', related_name='form_fields')
  485. class FormPage(AbstractEmailForm):
  486. """Form Page with customised submissions listing view"""
  487. # set custom view class as class attribute
  488. submissions_list_view_class = CustomSubmissionsListView
  489. intro = RichTextField(blank=True)
  490. thank_you_text = RichTextField(blank=True)
  491. # content_panels = ...
  492. Adding a custom field type
  493. --------------------------
  494. First, make the new field type available in the page editor by changing your ``FormField`` model.
  495. * Create a new set of choices which includes the original ``FORM_FIELD_CHOICES`` along with new field types you want to make available.
  496. * Each choice must contain a unique key and a human readable name of the field, e.g. ``('slug', 'URL Slug')``
  497. * Override the ``field_type`` field in your ``FormField`` model with ``choices`` attribute using these choices.
  498. * You will need to run ``./manage.py makemigrations`` and ``./manage.py migrate`` after this step.
  499. Then, create and use a new form builder class.
  500. * Define a new form builder class that extends the ``FormBuilder`` class.
  501. * Add a method that will return a created Django form field for the new field type.
  502. * Its name must be in the format: ``create_<field_type_key>_field``, e.g. ``create_slug_field``
  503. * Override the ``form_builder`` attribute in your form page model to use your new form builder class.
  504. Example:
  505. .. code-block:: python
  506. from django import forms
  507. from django.db import models
  508. from modelcluster.fields import ParentalKey
  509. from wagtail.contrib.forms.forms import FormBuilder
  510. from wagtail.contrib.forms.models import (
  511. AbstractEmailForm, AbstractFormField, FORM_FIELD_CHOICES)
  512. class FormField(AbstractFormField):
  513. # extend the built in field type choices
  514. # our field type key will be 'ipaddress'
  515. CHOICES = FORM_FIELD_CHOICES + (('ipaddress', 'IP Address'),)
  516. page = ParentalKey('FormPage', related_name='form_fields')
  517. # override the field_type field with extended choices
  518. field_type = models.CharField(
  519. verbose_name='field type',
  520. max_length=16,
  521. # use the choices tuple defined above
  522. choices=CHOICES
  523. )
  524. class CustomFormBuilder(FormBuilder):
  525. # create a function that returns an instanced Django form field
  526. # function name must match create_<field_type_key>_field
  527. def create_ipaddress_field(self, field, options):
  528. # return `forms.GenericIPAddressField(**options)` not `forms.SlugField`
  529. # returns created a form field with the options passed in
  530. return forms.GenericIPAddressField(**options)
  531. class FormPage(AbstractEmailForm):
  532. # intro, thank_you_text, edit_handlers, etc...
  533. # use custom form builder defined above
  534. form_builder = CustomFormBuilder
  535. .. _form_builder_render_email:
  536. Custom ``render_email`` method
  537. ------------------------------
  538. If you want to change the content of the email that is sent when a form submits you can override the ``render_email`` method.
  539. To do this, you need to:
  540. * Ensure you have your form model defined that extends ``wagtail.contrib.forms.models.AbstractEmailForm``.
  541. * Override the ``render_email`` method in your page model.
  542. Example:
  543. .. code-block:: python
  544. from datetime import date
  545. # ... additional wagtail imports
  546. from wagtail.contrib.forms.models import AbstractEmailForm
  547. class FormPage(AbstractEmailForm):
  548. # ... fields, content_panels, etc
  549. def render_email(self, form):
  550. # Get the original content (string)
  551. email_content = super().render_email(form)
  552. # Add a title (not part of original method)
  553. title = '{}: {}'.format('Form', self.title)
  554. content = [title, '', email_content, '']
  555. # Add a link to the form page
  556. content.append('{}: {}'.format('Submitted Via', self.full_url))
  557. # Add the date the form was submitted
  558. submitted_date_str = date.today().strftime('%x')
  559. content.append('{}: {}'.format('Submitted on', submitted_date_str))
  560. # Content is joined with a new line to separate each text line
  561. content = '\n'.join(content)
  562. return content
  563. Custom ``send_mail`` method
  564. ---------------------------
  565. If you want to change the subject or some other part of how an email is sent when a form submits you can override the ``send_mail`` method.
  566. To do this, you need to:
  567. * Ensure you have your form model defined that extends ``wagtail.contrib.forms.models.AbstractEmailForm``.
  568. * In your models.py file, import the ``wagtail.admin.mail.send_mail`` function.
  569. * Override the ``send_mail`` method in your page model.
  570. Example:
  571. .. code-block:: python
  572. from datetime import date
  573. # ... additional wagtail imports
  574. from wagtail.admin.mail import send_mail
  575. from wagtail.contrib.forms.models import AbstractEmailForm
  576. class FormPage(AbstractEmailForm):
  577. # ... fields, content_panels, etc
  578. def send_mail(self, form):
  579. # `self` is the FormPage, `form` is the form's POST data on submit
  580. # Email addresses are parsed from the FormPage's addresses field
  581. addresses = [x.strip() for x in self.to_address.split(',')]
  582. # Subject can be adjusted (adding submitted date), be sure to include the form's defined subject field
  583. submitted_date_str = date.today().strftime('%x')
  584. subject = f"{self.subject} - {submitted_date_str}"
  585. send_mail(subject, self.render_email(form), addresses, self.from_address,)