2
0

models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. from django.conf import settings
  2. from django.contrib.contenttypes.fields import GenericRelation
  3. from django.db import models
  4. from django.utils.translation import gettext as _
  5. from modelcluster.fields import ParentalKey
  6. from modelcluster.models import ClusterableModel
  7. from wagtail.admin.panels import (
  8. FieldPanel,
  9. FieldRowPanel,
  10. HelpPanel,
  11. InlinePanel,
  12. MultiFieldPanel,
  13. PublishingPanel,
  14. )
  15. from wagtail.api import APIField
  16. from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
  17. from wagtail.contrib.forms.panels import FormSubmissionsPanel
  18. from wagtail.contrib.settings.models import (
  19. BaseGenericSetting,
  20. BaseSiteSetting,
  21. register_setting,
  22. )
  23. from wagtail.fields import RichTextField, StreamField
  24. from wagtail.images.models import Image
  25. from wagtail.models import (
  26. Collection,
  27. DraftStateMixin,
  28. LockableMixin,
  29. Page,
  30. PreviewableMixin,
  31. RevisionMixin,
  32. Task,
  33. TaskState,
  34. TranslatableMixin,
  35. WorkflowMixin,
  36. )
  37. from wagtail.search import index
  38. from bakerydemo.headless import CustomHeadlessMixin
  39. from .blocks import BaseStreamBlock
  40. # Allow filtering by collection
  41. Image.api_fields = [APIField("collection")]
  42. class Person(
  43. WorkflowMixin,
  44. DraftStateMixin,
  45. LockableMixin,
  46. RevisionMixin,
  47. PreviewableMixin,
  48. index.Indexed,
  49. ClusterableModel,
  50. ):
  51. """
  52. A Django model to store Person objects.
  53. It is registered using `register_snippet` as a function in wagtail_hooks.py
  54. to allow it to have a menu item within a custom menu item group.
  55. `Person` uses the `ClusterableModel`, which allows the relationship with
  56. another model to be stored locally to the 'parent' model (e.g. a PageModel)
  57. until the parent is explicitly saved. This allows the editor to use the
  58. 'Preview' button, to preview the content, without saving the relationships
  59. to the database.
  60. https://github.com/wagtail/django-modelcluster
  61. """
  62. first_name = models.CharField("First name", max_length=254)
  63. last_name = models.CharField("Last name", max_length=254)
  64. job_title = models.CharField("Job title", max_length=254)
  65. image = models.ForeignKey(
  66. "wagtailimages.Image",
  67. null=True,
  68. blank=True,
  69. on_delete=models.SET_NULL,
  70. related_name="+",
  71. )
  72. workflow_states = GenericRelation(
  73. "wagtailcore.WorkflowState",
  74. content_type_field="base_content_type",
  75. object_id_field="object_id",
  76. related_query_name="person",
  77. for_concrete_model=False,
  78. )
  79. revisions = GenericRelation(
  80. "wagtailcore.Revision",
  81. content_type_field="base_content_type",
  82. object_id_field="object_id",
  83. related_query_name="person",
  84. for_concrete_model=False,
  85. )
  86. panels = [
  87. MultiFieldPanel(
  88. [
  89. FieldRowPanel(
  90. [
  91. FieldPanel("first_name"),
  92. FieldPanel("last_name"),
  93. ]
  94. )
  95. ],
  96. "Name",
  97. ),
  98. FieldPanel("job_title"),
  99. FieldPanel("image"),
  100. PublishingPanel(),
  101. ]
  102. search_fields = [
  103. index.SearchField("first_name"),
  104. index.SearchField("last_name"),
  105. index.FilterField("job_title"),
  106. index.AutocompleteField("first_name"),
  107. index.AutocompleteField("last_name"),
  108. ]
  109. api_fields = [
  110. APIField("first_name"),
  111. APIField("last_name"),
  112. APIField("job_title"),
  113. APIField("image"),
  114. ]
  115. @property
  116. def thumb_image(self):
  117. # Returns an empty string if there is no profile pic or the rendition
  118. # file can't be found.
  119. try:
  120. return self.image.get_rendition("fill-50x50").img_tag()
  121. except: # noqa: E722 FIXME: remove bare 'except:'
  122. return ""
  123. @property
  124. def preview_modes(self):
  125. return PreviewableMixin.DEFAULT_PREVIEW_MODES + [("blog_post", _("Blog post"))]
  126. def __str__(self):
  127. return "{} {}".format(self.first_name, self.last_name)
  128. def get_preview_template(self, request, mode_name):
  129. from bakerydemo.blog.models import BlogPage
  130. if mode_name == "blog_post":
  131. return BlogPage.template
  132. return "base/preview/person.html"
  133. def get_preview_context(self, request, mode_name):
  134. from bakerydemo.blog.models import BlogPage
  135. context = super().get_preview_context(request, mode_name)
  136. if mode_name == self.default_preview_mode:
  137. return context
  138. page = BlogPage.objects.filter(blog_person_relationship__person=self).first()
  139. if page:
  140. # Use the page authored by this person if available,
  141. # and replace the instance from the database with the edited instance
  142. page.authors = [
  143. self if author.pk == self.pk else author for author in page.authors()
  144. ]
  145. # The authors() method only shows live authors, so make sure the instance
  146. # is included even if it's not live as this is just a preview
  147. if not self.live:
  148. page.authors.append(self)
  149. else:
  150. # Otherwise, get the first page and simulate the person as the author
  151. page = BlogPage.objects.first()
  152. page.authors = [self]
  153. context["page"] = page
  154. return context
  155. class Meta:
  156. verbose_name = "person"
  157. verbose_name_plural = "people"
  158. class FooterText(
  159. DraftStateMixin,
  160. RevisionMixin,
  161. PreviewableMixin,
  162. TranslatableMixin,
  163. models.Model,
  164. ):
  165. """
  166. This provides editable text for the site footer. Again it is registered
  167. using `register_snippet` as a function in wagtail_hooks.py to be grouped
  168. together with the Person model inside the same main menu item. It is made
  169. accessible on the template via a template tag defined in base/templatetags/
  170. navigation_tags.py
  171. """
  172. body = RichTextField()
  173. revisions = GenericRelation(
  174. "wagtailcore.Revision",
  175. content_type_field="base_content_type",
  176. object_id_field="object_id",
  177. related_query_name="footer_text",
  178. for_concrete_model=False,
  179. )
  180. panels = [
  181. FieldPanel("body"),
  182. PublishingPanel(),
  183. ]
  184. api_fields = [
  185. APIField("body"),
  186. ]
  187. def __str__(self):
  188. return "Footer text"
  189. def get_preview_template(self, request, mode_name):
  190. return "base.html"
  191. def get_preview_context(self, request, mode_name):
  192. return {"footer_text": self.body}
  193. class Meta(TranslatableMixin.Meta):
  194. verbose_name = "footer text"
  195. verbose_name_plural = "footer text"
  196. class StandardPage(CustomHeadlessMixin, Page):
  197. """
  198. A generic content page. On this demo site we use it for an about page but
  199. it could be used for any type of page content that only needs a title,
  200. image, introduction and body field
  201. """
  202. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  203. image = models.ForeignKey(
  204. "wagtailimages.Image",
  205. null=True,
  206. blank=True,
  207. on_delete=models.SET_NULL,
  208. related_name="+",
  209. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  210. )
  211. body = StreamField(
  212. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  213. )
  214. content_panels = Page.content_panels + [
  215. FieldPanel("introduction"),
  216. FieldPanel("body"),
  217. FieldPanel("image"),
  218. ]
  219. api_fields = [
  220. APIField("introduction"),
  221. APIField("image"),
  222. APIField("body"),
  223. ]
  224. class HomePage(CustomHeadlessMixin, Page):
  225. """
  226. The Home Page. This looks slightly more complicated than it is. You can
  227. see if you visit your site and edit the homepage that it is split between
  228. a:
  229. - Hero area
  230. - Body area
  231. - A promotional area
  232. - Moveable featured site sections
  233. """
  234. # Hero section of HomePage
  235. image = models.ForeignKey(
  236. "wagtailimages.Image",
  237. null=True,
  238. blank=True,
  239. on_delete=models.SET_NULL,
  240. related_name="+",
  241. help_text="Homepage image",
  242. )
  243. hero_text = models.CharField(
  244. max_length=255, help_text="Write an introduction for the bakery"
  245. )
  246. hero_cta = models.CharField(
  247. verbose_name="Hero CTA",
  248. max_length=255,
  249. help_text="Text to display on Call to Action",
  250. )
  251. hero_cta_link = models.ForeignKey(
  252. "wagtailcore.Page",
  253. null=True,
  254. blank=True,
  255. on_delete=models.SET_NULL,
  256. related_name="+",
  257. verbose_name="Hero CTA link",
  258. help_text="Choose a page to link to for the Call to Action",
  259. )
  260. # Body section of the HomePage
  261. body = StreamField(
  262. BaseStreamBlock(),
  263. verbose_name="Home content block",
  264. blank=True,
  265. use_json_field=True,
  266. )
  267. # Promo section of the HomePage
  268. promo_image = models.ForeignKey(
  269. "wagtailimages.Image",
  270. null=True,
  271. blank=True,
  272. on_delete=models.SET_NULL,
  273. related_name="+",
  274. help_text="Promo image",
  275. )
  276. promo_title = models.CharField(
  277. blank=True, max_length=255, help_text="Title to display above the promo copy"
  278. )
  279. promo_text = RichTextField(
  280. null=True, blank=True, max_length=1000, help_text="Write some promotional copy"
  281. )
  282. # Featured sections on the HomePage
  283. # You will see on templates/base/home_page.html that these are treated
  284. # in different ways, and displayed in different areas of the page.
  285. # Each list their children items that we access via the children function
  286. # that we define on the individual Page models e.g. BlogIndexPage
  287. featured_section_1_title = models.CharField(
  288. blank=True, max_length=255, help_text="Title to display above the promo copy"
  289. )
  290. featured_section_1 = models.ForeignKey(
  291. "wagtailcore.Page",
  292. null=True,
  293. blank=True,
  294. on_delete=models.SET_NULL,
  295. related_name="+",
  296. help_text="First featured section for the homepage. Will display up to "
  297. "three child items.",
  298. verbose_name="Featured section 1",
  299. )
  300. featured_section_2_title = models.CharField(
  301. blank=True, max_length=255, help_text="Title to display above the promo copy"
  302. )
  303. featured_section_2 = models.ForeignKey(
  304. "wagtailcore.Page",
  305. null=True,
  306. blank=True,
  307. on_delete=models.SET_NULL,
  308. related_name="+",
  309. help_text="Second featured section for the homepage. Will display up to "
  310. "three child items.",
  311. verbose_name="Featured section 2",
  312. )
  313. featured_section_3_title = models.CharField(
  314. blank=True, max_length=255, help_text="Title to display above the promo copy"
  315. )
  316. featured_section_3 = models.ForeignKey(
  317. "wagtailcore.Page",
  318. null=True,
  319. blank=True,
  320. on_delete=models.SET_NULL,
  321. related_name="+",
  322. help_text="Third featured section for the homepage. Will display up to "
  323. "six child items.",
  324. verbose_name="Featured section 3",
  325. )
  326. content_panels = Page.content_panels + [
  327. MultiFieldPanel(
  328. [
  329. FieldPanel("image"),
  330. FieldPanel("hero_text"),
  331. MultiFieldPanel(
  332. [
  333. FieldPanel("hero_cta"),
  334. FieldPanel("hero_cta_link"),
  335. ]
  336. ),
  337. ],
  338. heading="Hero section",
  339. ),
  340. HelpPanel("This is a help panel"),
  341. MultiFieldPanel(
  342. [
  343. FieldPanel("promo_image"),
  344. FieldPanel("promo_title"),
  345. FieldPanel("promo_text"),
  346. ],
  347. heading="Promo section",
  348. help_text="This is just a help text",
  349. ),
  350. FieldPanel("body"),
  351. MultiFieldPanel(
  352. [
  353. MultiFieldPanel(
  354. [
  355. FieldPanel("featured_section_1_title"),
  356. FieldPanel("featured_section_1"),
  357. ]
  358. ),
  359. MultiFieldPanel(
  360. [
  361. FieldPanel("featured_section_2_title"),
  362. FieldPanel("featured_section_2"),
  363. ]
  364. ),
  365. MultiFieldPanel(
  366. [
  367. FieldPanel("featured_section_3_title"),
  368. FieldPanel("featured_section_3"),
  369. ]
  370. ),
  371. ],
  372. heading="Featured homepage sections",
  373. ),
  374. ]
  375. api_fields = [
  376. APIField("image"),
  377. APIField("hero_text"),
  378. APIField("hero_cta"),
  379. APIField("hero_cta_link"),
  380. APIField("body"),
  381. APIField("promo_image"),
  382. APIField("promo_title"),
  383. APIField("promo_text"),
  384. APIField("featured_section_1_title"),
  385. APIField("featured_section_1"),
  386. APIField("featured_section_2_title"),
  387. APIField("featured_section_2"),
  388. APIField("featured_section_3_title"),
  389. APIField("featured_section_3"),
  390. ]
  391. def __str__(self):
  392. return self.title
  393. class GalleryPage(CustomHeadlessMixin, Page):
  394. """
  395. This is a page to list locations from the selected Collection. We use a Q
  396. object to list any Collection created (/admin/collections/) even if they
  397. contain no items. In this demo we use it for a GalleryPage,
  398. and is intended to show the extensibility of this aspect of Wagtail
  399. """
  400. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  401. image = models.ForeignKey(
  402. "wagtailimages.Image",
  403. null=True,
  404. blank=True,
  405. on_delete=models.SET_NULL,
  406. related_name="+",
  407. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  408. )
  409. body = StreamField(
  410. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  411. )
  412. collection = models.ForeignKey(
  413. Collection,
  414. limit_choices_to=~models.Q(name__in=["Root"]),
  415. null=True,
  416. blank=True,
  417. on_delete=models.SET_NULL,
  418. help_text="Select the image collection for this gallery.",
  419. )
  420. content_panels = Page.content_panels + [
  421. FieldPanel("introduction"),
  422. FieldPanel("body"),
  423. FieldPanel("image"),
  424. FieldPanel("collection"),
  425. ]
  426. # Defining what content type can sit under the parent. Since it's a blank
  427. # array no subpage can be added
  428. subpage_types = []
  429. api_fields = [
  430. APIField("introduction"),
  431. APIField("image"),
  432. APIField("body"),
  433. APIField("collection"),
  434. ]
  435. class FormField(AbstractFormField):
  436. """
  437. Wagtailforms is a module to introduce simple forms on a Wagtail site. It
  438. isn't intended as a replacement to Django's form support but as a quick way
  439. to generate a general purpose data-collection form or contact form
  440. without having to write code. We use it on the site for a contact form. You
  441. can read more about Wagtail forms at:
  442. https://docs.wagtail.org/en/stable/reference/contrib/forms/index.html
  443. """
  444. page = ParentalKey("FormPage", related_name="form_fields", on_delete=models.CASCADE)
  445. class FormPage(CustomHeadlessMixin, AbstractEmailForm):
  446. image = models.ForeignKey(
  447. "wagtailimages.Image",
  448. null=True,
  449. blank=True,
  450. on_delete=models.SET_NULL,
  451. related_name="+",
  452. )
  453. body = StreamField(BaseStreamBlock(), use_json_field=True)
  454. thank_you_text = RichTextField(blank=True)
  455. # Note how we include the FormField object via an InlinePanel using the
  456. # related_name value
  457. content_panels = AbstractEmailForm.content_panels + [
  458. FormSubmissionsPanel(),
  459. FieldPanel("image"),
  460. FieldPanel("body"),
  461. InlinePanel("form_fields", heading="Form fields", label="Field"),
  462. FieldPanel("thank_you_text"),
  463. MultiFieldPanel(
  464. [
  465. FieldRowPanel(
  466. [
  467. FieldPanel("from_address"),
  468. FieldPanel("to_address"),
  469. ]
  470. ),
  471. FieldPanel("subject"),
  472. ],
  473. "Email",
  474. ),
  475. ]
  476. api_fields = [
  477. APIField("form_fields"),
  478. APIField("from_address"),
  479. APIField("to_address"),
  480. APIField("subject"),
  481. APIField("image"),
  482. APIField("body"),
  483. APIField("thank_you_text"),
  484. ]
  485. @register_setting(icon="cog")
  486. class GenericSettings(ClusterableModel, BaseGenericSetting):
  487. mastodon_url = models.URLField(verbose_name="Mastodon URL", blank=True)
  488. github_url = models.URLField(verbose_name="GitHub URL", blank=True)
  489. organisation_url = models.URLField(verbose_name="Organisation URL", blank=True)
  490. panels = [
  491. MultiFieldPanel(
  492. [
  493. FieldPanel("github_url"),
  494. FieldPanel("mastodon_url"),
  495. FieldPanel("organisation_url"),
  496. ],
  497. "Social settings",
  498. )
  499. ]
  500. @register_setting(icon="site")
  501. class SiteSettings(BaseSiteSetting):
  502. title_suffix = models.CharField(
  503. verbose_name="Title suffix",
  504. max_length=255,
  505. help_text="The suffix for the title meta tag e.g. ' | The Wagtail Bakery'",
  506. default="The Wagtail Bakery",
  507. )
  508. panels = [
  509. FieldPanel("title_suffix"),
  510. ]
  511. class UserApprovalTaskState(TaskState):
  512. pass
  513. class UserApprovalTask(Task):
  514. """
  515. Based on https://docs.wagtail.org/en/stable/extending/custom_tasks.html.
  516. """
  517. user = models.ForeignKey(
  518. settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False
  519. )
  520. admin_form_fields = Task.admin_form_fields + ["user"]
  521. task_state_class = UserApprovalTaskState
  522. # prevent editing of `user` after the task is created
  523. # by default, this attribute contains the 'name' field to prevent tasks from being renamed
  524. admin_form_readonly_on_edit_fields = Task.admin_form_readonly_on_edit_fields + [
  525. "user"
  526. ]
  527. def user_can_access_editor(self, page, user):
  528. return user == self.user
  529. def page_locked_for_user(self, page, user):
  530. return user != self.user
  531. def get_actions(self, page, user):
  532. if user == self.user:
  533. return [
  534. ("approve", "Approve", False),
  535. ("reject", "Reject", False),
  536. ("cancel", "Cancel", False),
  537. ]
  538. else:
  539. return []
  540. def on_action(self, task_state, user, action_name, **kwargs):
  541. if action_name == "cancel":
  542. return task_state.workflow_state.cancel(user=user)
  543. else:
  544. return super().on_action(task_state, user, action_name, **kwargs)
  545. def get_task_states_user_can_moderate(self, user, **kwargs):
  546. if user == self.user:
  547. # get all task states linked to the (base class of) current task
  548. return TaskState.objects.filter(
  549. status=TaskState.STATUS_IN_PROGRESS, task=self.task_ptr
  550. )
  551. else:
  552. return TaskState.objects.none()
  553. @classmethod
  554. def get_description(cls):
  555. return _("Only a specific user can approve this task")