【问题标题】:Adding User model to the StructBlock class将用户模型添加到 StructBlock 类
【发布时间】:2021-03-15 20:00:42
【问题描述】:

我正在尝试创建一个简单的博客页面,其中包含图像、内容、发布日期和发布用户。 但我不认为 wagtail 允许我将用户模型放入我的块中。

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"

我的目标是每次用户发布新公告时,他/她的名字都应该出现。不知道我该怎么做,因为在块中我无法添加用户模型,以便用户的详细信息将与内容/图像等一起保存。

类似的东西。

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"

请帮忙谢谢

【问题讨论】:

    标签: django django-models wagtail wagtail-streamfield


    【解决方案1】:

    我认为您不能在 Streamfield Block 类中使用ForeignKey

    如果您可以显示一个简单的用户选择小部件,请尝试将ChooserBlock 子类化(请参阅here)。

    如果您需要自动分配登录用户,您也许可以编写自己的块类型,但 1- 它更复杂,因为您必须弄清楚 Streamfields 如何在内部工作,以及 2- 如果我没记错的话,您无法从块定义中访问 request 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 2018-09-12
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      相关资源
      最近更新 更多