Wagtail Custom Pages? - wagtail

I'm totally new to Wagtail/ Django.
Here's what I am trying to achieve:
I'd like to have an ability in the backend of my Wagtail CMS install to create 'pages' or 'posts' that follow a strict template.
The template would have custom fields like 'header' and aim content' etc.
I'm sure that this is possible, I'd just be interested to know how I'd go about achieving this?
For example, does anyone know if Wagtail has a plugin or other to enable this?
Thanks for all help/ direction.

You want to create pages and posts that follow a strict template: that's exactly what Django and Wagtail let you do. But there's one catch: Wagtail takes this a step further and lets you move entire sections of a page — these are called Streamfields. It's an amazing feature, to be honest.
Here's an example to get you started (note: this is untested and not linted)
# -*- coding: utf-8 -*-
"""Basic Page model."""
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, StreamFieldPanel
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from your_custom_app.streams import streamfields
class BasicPage(Page):
"""A basic page class."""
template = "templates/pages/basic_page.html"
parent_page_type = ["pages.HomePage", "pages.BasicPage"]
subpage_types = ["pages.BasicPage"]
header = models.CharField(max_length=100)
content = StreamField(
('streamfield_name', streamfields.CustomStreamfield()),
# ... More streams
null=True,
blank=True,
)
# Other additional fields you want on your page.
# Panels are how you lay out your pages in the /admin/
content_panels = [
FieldPanel("title", classname="full title"),
FieldPanel("header"),
# FieldPanel("other_fields"),
StreamFieldPanel("content"),
]
settings_panels = Page.settings_panels + [] # Custom settings panel
promote_panels = Page.promote_panels + [] # Custom promote panel
class Meta:
"""Meta information."""
verbose_name = "Basic Page"
verbose_name_plural = "Basic Pages"
You can also download and setup the Wagtail Bakery Demo, it has a lot of great examples in it.

Related

How do I access a model in wagtail which is linked by a central model as a many-to-many relationship?

I'm working with wagtail and implemented a many-to-many relationship between page models by using a central model which handles this relationship. I did the same, as what is written in this issue: Wagtail many-to-many links between different Page models and it works so far in the wagtail admin.
Now I struggle with accessing the information of the related page model and displaying it on a template. So let's assume, that I use the code from the mentioned issue:
Example Code
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, PageChooserPanel
class PersonPageSitePageRelation(models.Model):
person = ParentalKey('app.PersonPage', on_delete=models.CASCADE, related_name='sites')
site = ParentalKey('app.SitePage', on_delete=models.CASCADE, related_name='people')
# Optional: some additional fields (e.g. 'note') for this relation
# Important: NOT setting any `panels` here, will be set individually for each 'direction'
class Meta:
unique_together = ('person', 'site')
class PersonPage(Page):
# ... fields (note: `sites` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `sites`, but the panels available will be the PersonPageSitePageRelation's field `site`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('sites', label='Related Sites', [PageChooserPanel('site')]),
]
class SitePage(Page):
# ... fields (note: `people` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `people`, but the panels available will be the PersonPageSitePageRelation's field `person`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('people', label='Related People', panels=[PageChooserPanel('person')]),
]
I'm able to select related person-pages on a site page by a page-chooser-panel. How can I now display all persons of one site on a site_page.html template?
If I'm accessing one specific SidePage via site_page.html I tried the tag {{page.people}} but I just see PersonPageSitePageRelation.None. I'm so confused by the use of the central PersonPageSitePageRelation model and I don't find any similar case in other issues.
Thank you a lot in advance!

Wagtail many-to-many links between different Page models

Does anyone have or know of a recipe (sample code and/or instructions) on setting up many-to-many relationships between different Page models? If I have PersonPage and SitePage models, how do I connect the pages (a person can work at multiple sites and a site can have multiple people working there)?
Here's what I've found related to, but not directly on, this topic—
Wagtail docs: from a search for "many-to-many" the only hit is in the section on the taggit module (Recipes page).
Wagtail docs: the only reference to the ParentalManyToManyField is a demo of how it can be used to create M2Ms between pages and categories (Tutorial)
This 2015 post on M2M relationships in Wagtail (it's referenced in an SO 'answer' to basically the same question I'm asking here). Although it doesn't discuss page-page relationships the approach presented might be adapted to work. My modified imitation failed with various errors depending on how I tried to set up the InlinePanel call — but the sample code from the post fails in just the same ways, so either it wasn't tested or it's been made obsolete in 2.x.
class PersonPage(Page):
pass
PersonPage.content_panels = [
InlinePanel('ps_links', label='PS Links'),
]
class PersonSitePageLink():
spage = models.ForeignKey('SitePage', on_delete=models.SET_NULL, related_name='sites')
ppage = ParentalKey('PersonPage', related_name='ps_links', on_delete=models.SET_NULL,)
panels = [
FieldPanel('spage')
]
class SitePage(Page):
pass
This technique works fine for relating a Page model to itself, but expanding it to encompass two distinct models creates two parallel but unconnected sets of relationships (you can pick arbitrary Bug pages to link to any Plant page, or vice versa, but the Plants you picked don't show when you edit Bugs). I see why in the code, I think, but I don't see how to make a single M2M connection between the two pages.
class PlantPage(Page):
related_bugs = ParentalManyToManyField('BugPage', blank=True)
content_panels = Page.content_panels + [
FieldPanel('related_bugs'),
]
class BugPage(Page):
related_plants = ParentalManyToManyField('PlantPage', blank=True)
content_panels = Page.content_panels + [
FieldPanel('related_plants'),
]
This one also only talks about intra-page model (rather than inter-page model) M2Ms. (It is pre-ParentalManyToManyField and in fact only available from the Wayback Machine.)
I hope this helps, I took inspiration from this article about moving from ParentalManyToManyField to a central model that 'links' each page from this AccordBox article.
It turns out that InlinePanel does not fully support ParentalManyToManyField, hence the issues you were running into.
I was able to implement a refined approach to your option one above and it should solve your problem.
A reminder that all Page models already extend ClusterableModel so there is no need to add that to any models you create.
Overview
Create a new 'relation' that extends models.Model which will be the relation between these two page models.
Each field within this new model will be the two page types via the model-cluster ParentalKey each with a logical related_name set that is the OTHER side of the relationship.
No need to set panels on this model as we will declare the panels individually via the panels kwarg to InlinePanel - see the InlinePanel docs.
Finally, each individual Page's content_panels has an InlinePanel added that refers to the central relation model indirectly via that model's related_name, adding the other side reference to PageChooserPanel.
Example Code
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, PageChooserPanel
class PersonPageSitePageRelation(models.Model):
person = ParentalKey('app.PersonPage', on_delete=models.CASCADE, related_name='sites')
site = ParentalKey('app.SitePage', on_delete=models.CASCADE, related_name='people')
# Optional: some additional fields (e.g. 'note') for this relation
# Important: NOT setting any `panels` here, will be set individually for each 'direction'
class Meta:
unique_together = ('person', 'site')
class PersonPage(Page):
# ... fields (note: `sites` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `sites`, but the panels available will be the PersonPageSitePageRelation's field `site`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('sites', label='Related Sites', [PageChooserPanel('site')]),
]
class SitePage(Page):
# ... fields (note: `people` does NOT need to be declared as a field)
# Now we add an `InlinePanel` that will connect to the parental connection to PersonPageSitePageRelation via the related name `people`, but the panels available will be the PersonPageSitePageRelation's field `person`
content_panels = Page.content_panels + [
# ... other FieldPanel etc
InlinePanel('people', label='Related People', panels=[PageChooserPanel('person')]),
]
Further Reading
Read about Django Modelcluster - which is the library that ParentalKey comes from.

Can I use a recursive ParentalKey in Wagtail?

Say I have the following model in a Wagtail app:
# models.py
from django.db import models
from django.db.models.deletion import CASCADE
from wagtail.admin.edit_handlers import InlinePanel, FieldPanel
from modelcluster.models import ParentalKey, ClusterableModel
class Person(ClusterableModel):
name = models.CharField(max_length=300)
contact_for = ParentalKey(
'self', on_delete=CASCADE, null=True, related_name='contacts'
)
panels = [
FieldPanel('name'),
FieldPanel('contact_for'),
InlinePanel('contacts')
]
And the following hooks:
# wagtail_hooks.py
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from home.models import Person
class PersonAdmin(ModelAdmin):
model = Person
menu_label = 'People'
menu_icon = 'list-ul'
menu_order = 200
add_to_settings_menu = False
exclude_from_explorer = False
list_display = ('name',)
search_fields = ('name',)
list_filter = ('contact_for',)
modeladmin_register(PersonAdmin)
When running the above and navigating to Admin > People > Add Person I will get a RecursionError exception (maximum recursion depth exceeded).
I'm guessing this is a Wagtail related issue, because I can use the class as intended in IPython:
./manage.py shell -i ipython
In [1]: from home.models import Person
In [2]: mike = Person(name='Mike')
In [3]: mike.contacts = [Person(name='Sam'), Person(name='John')]
In [4]: mike.contacts
Out[4]: <modelcluster.fields.create_deferring_foreign_related_manager.<locals>.DeferringRelatedManager at 0x7f36e9548af0>
In [5]: mike.save()
In [6]: [person.name for person in Person.objects.all()]
Out[6]: ['Mike', 'Sam', 'John']
In [7]: Person.objects.all()[1].contact_for.name
Out[7]: 'Mike'
So, is there a way I can make use of a recursive ParentalKey in Wagtail? What am I doing wrong/missing?
Edit: I just found this answer. So I'm wondering if I should even be trying to use ParentalKey (and ParentalManyToManyField) for non Page models.
Edit 2: For anyone interested, I ended up splitting my Model to avoid a recursive key. InlinePanels do work with ModelAdmin classes, it's just Wagtail doesn't seem to support recursive keys. I have also opted to use Snippets and SnippetChooserPanel where it felt appropriate.
A ParentalKey means that the child model is notionally treated as 'part of' the parent model and doesn't exist as an independent entity - for example, an image gallery being part of a page - for purposes such as versioning, and moderation workflow. (In Wagtail, non-page models handled through snippets or ModelAdmin don't have these features, but in order for them to share the same InlinePanel mechanism as pages, they also use ParentalKey.)
In this case, a Person is not part of another Person, and needs to be editable independently of the 'parent', so a ParentalKey isn't appropriate here. Instead, you should use a ForeignKey, which just indicates some relation between the models. This does mean that you can't use an InlinePanel to manage multiple Person records within the same view - you'll have to edit them separately, and use something like SnippetChooserPanel or a simple dropdown to set up the relations between them.

How would I extend the wagtailmenus LinkPage to add a generic picture

I have been using the AbstractLinkPage model from wagtailmenus in my site for a while now. I find it quite useful.
Source: wagtailmenus AbstractLinkPage model
My site is building cards from children pages and adds banner images from children pages automatically to these cards. Some of the children pages are LinkPages.
How can I extend the subclassed LinkPage (from AbstractLinkPage) to add a generic image which can be used as a card image?
I have added the field:
class LinkPage(AbstractLinkPage):
card_image = models.ForeignKey(
get_image_model_string(),
null=True,
blank=True,
related_name='+',
on_delete=models.SET_NULL,
)
content_panels = AbstractLinkPage.content_panels + [
ImageChooserPanel("card_image"),
]
However the image card_image field does not show in the admin interface.
Any help to move forward is appreciated.
Wagtailmenus uses it's own tabbed interface (in wagtailmenus.panels):
linkpage_tab = ObjectList(
linkpage_panels, heading=_("Settings"), classname="settings"
)
linkpage_edit_handler = TabbedInterface([linkpage_tab])
So what you have to do is to create a new ObjectList:
from wagtailmenus.panels import linkpage_panels
from wagtail.admin.edit_handlers import ObjectList, TabbedInterface
my_linkpage_tab = ObjectList(
linkpage_panels + [ImageChooserPanel("card_image")],
heading=_("Settings"), classname="settings"
)
.. and add it to your class:
class LinkPage(AbstractLinkPage):
[..]
edit_handler = TabbedInterface([my_linkpage_tab])

Why is the SnippetChooserPanel not opening in Wagtail?

Some time ago I stopped using #register_snippet to decorate Snippets. This takes the Snippet out of the snippets section of admin.
Instead I used the wagtail_hooks.py to show the snippet directly in the left admin panel for user convenience. See below. This works nicely as the user can go directly to the snippet and you can also alter the displayed fields and ordering of fields - nice.
So in the below example I removed the line that says #register_snippet. What's the catch? The SnippetChooserPanel does not work! Later I was building a complex model and the SnippetChooserPanel did not work. I wasted quite a bit of time thinking the problem was in the complexity of my model. I want to save others' time!
wagtail_hooks.py:
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from wagtail.wagtailsnippets.models import register_snippet
from demo.models import Advert
class AdvertAdmin(ModelAdmin):
model = Advert
modeladmin_register(AdvertAdmin)
Here is the snippet example from Wagtail: snippets
#register_snippet #<------- Source of issue (I removed this line!)
#python_2_unicode_compatible # provide equivalent __unicode__ and __str__ methods on Python 2
class Advert(models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
def __str__(self):
return self.text
class BookPage(Page):
advert = models.ForeignKey(
'demo.Advert',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
SnippetChooserPanel('advert'),
# ...
]
If you make your Snippets editable via modelAdmin you still need to apply the decorator #register_snippet. Otherwise the chooser panel route/view won't be available. This view is requested by the ajax request fired on SnippetChooser modal open. Missing #register snippet will trow a 404.
You can register menu items via construct_main_menu hook. You can use the same hook to remove exiting menu-items. If you do not want the 'Snippets' menu item remove it. In wagtail_hooks.py:
#hooks.register('construct_main_menu')
def hide_snippet(request, menu_items):
menu_items[:] = [item for item in menu_items if item.name != 'snippets']
The solution is always use #register_snippet decorator otherwise the SnippetChooserPanel doesn't work!
#register_snippet
#python_2_unicode_compatible
class Advert(models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
def __str__(self):
return self.text

Resources