2
0

models.py 19 KB

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