0

I'm trying to create a simple blog page with image,content,date posted and user who posted. But I don't think that wagtail allows me to put in the user model into my block.

class HomePage(Page):
    template_name = 'home/home_page.html'
    max_count = 1

    subtitle = models.CharField(max_length=200)

    content = StreamField(
        [
            ("title_and_text_block", AnnouncementBlock())
        ]
    )

    content_panels = Page.content_panels + [
        FieldPanel("subtitle"),
        StreamFieldPanel("content")
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, args, kwargs)
        context['posts'] = HomePage.objects.live().public()
        return context;
from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock


class AnnouncementBlock(blocks.StructBlock):
    title = blocks.CharBlock(required=True, help_text='Add your title')
    content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"])
    image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail')

    class Meta:
        template = "streams/title_and_text_block.html"
        icon = "edit"
        label = "Announcement"

My goal is everytime user posted a new announcement his/her name should appear. not sure how i can do that since in the block i cannot add the User model so that the user's detail will be saved along with the content/image etc.

something like this.

from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock
from django.conf import settings


class AnnouncementBlock(blocks.StructBlock):
    title = blocks.CharBlock(required=True, help_text='Add your title')
    content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"])
    image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail')

    #USER is not allowed here. error on the model
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    class Meta:
        template = "streams/title_and_text_block.html"
        icon = "edit"
        label = "Announcement"

Please help thanks

1 Answers1

0

I think you can't use a ForeignKey inside a Streamfield Block class.

If you're OK with displaying a simple user select widget, try to subclass a ChooserBlock (see here).

If you need to assign the logged in user automatically instead, you might be able to write your own block type but 1- it's more complicated as you will have to figure out how Streamfields work internally and 2- if I remember correctly, you can't access the request object from inside a block definition.

Benoît Vogel
  • 316
  • 3
  • 8