thht
thht

Reputation: 61

Access other object fields in StreamField / RichText field/block in wagtail

I would like to do the following:

  1. Create some django model (or wagtail page) that contains data.
  2. Create another Page type that includes a StreamField or RichtextField. 3.
  3. When the author or editor enters text in this field, he/she can have the information of this appear somewhere in the rendered output of the text. Preferably using common template techniques.

So, lets say, we have a model like this:

class Person(models.Model):
    name = models.CharField(max_length=30)

Then I have a normal page that uses a StreamField:

class NormalPage(Page):
    body = StreamField(block_types=[
        ('paragraph', blocks.RichTextBlock()),
    ])

    content_panels = Page.content_panels + [
        StreamFieldPanel('body')
    ]

I would like for the editor to choose which Person he/she would like from the database and the be able to do something like this in the RichTextBlock:

{{ person.name }}

Is this possible?

Upvotes: 2

Views: 510

Answers (1)

Dan Swain
Dan Swain

Reputation: 3098

In order to be able to choose a plain Django model, register it as a snippet as shown here, and then use SnippetChooserPanel to choose the person:

from wagtail.snippets.models import register_snippet

@register_snippet
class Person(models.Model):
    name = models.CharField(max_length=30)

And then if you want to associate a particular person with a particular page:

from wagtail.snippets.edit_handlers import SnippetChooserPanel

class NormalPage(Page):
    body = StreamField(block_types=[
        ('paragraph', blocks.RichTextBlock()),
    ])
    person = models.ForeignKeyField(Person)

    content_panels = Page.content_panels + [
        StreamFieldPanel('body'),
        SnippetChooserPanel('person'),
    ]

Upvotes: 1

Related Questions