【问题标题】:How to provide default value in Wagtail Page.title field?如何在 Wagtail Page.title 字段中提供默认值?
【发布时间】:2019-04-22 16:01:25
【问题描述】:

我所需要的只是随机生成的页面标题,其中包含一些内容:

class MyBasePage(Page):
    title = models.CharField(
        default=uuid4,
        verbose_name=_('title'),
        max_length=255,
        help_text=_("The page title as you'd like it to be seen by the public")
    )

class OtherPage(MyBasePage):
    pass

目前我被以下错误阻止:

django.core.exceptions.FieldError:类“MyBasePage”中的本地字段“title”与基类“Page”中的同名字段冲突。

任何想法如何实现这一目标? 为了方便,这里是url源代码。

【问题讨论】:

  • 你能添加“页面”模型的代码吗?看起来您可能在 Page 中有一个“标题”字段,因此您在 MyBasePage 中的标题导致了冲突。
  • @f71316 添加源代码网址。
  • 您不能通过在 MyBasePage 类中放置一个新的冲突“标题”来覆盖基本 Page 类的“标题”字段。 docs.djangoproject.com/en/dev/topics/db/models/… 也许使用您的保存功能来查找现有标题,如果它不存在,则将默认设置为 uuid...

标签: django python-3.x django-models wagtail


【解决方案1】:

您正在尝试覆盖 Wagtail 页面附带的 title 属性,您将收到此错误:

django.core.exceptions.FieldError: Local field 'title' in class 'MyBasePage' clashes with field of the same name from base class 'Page'.

如果你想覆盖 Wagtail title 默认值,你可以用这个 sn-p 代码设置它(最后一行是重要的):

class MyBasePage(Page):
    # Custom fields in here ...

MyBasePage._meta.get_field("title").default = "New Default Title"

最后,请注意最后一行在定义的类之外——这就是我们在一行代码中更改默认标题的方式。

【讨论】:

    【解决方案2】:

    我认为你必须使用模型的 pre_init 信号

    from django.db.models.signals import pre_init
    from django.dispatch import receiver
    
    @receiver(pre_save, sender=MyBasePage)
    def generate_home_title(sender, instance, *args, **kwargs):
        instance.title = randomly_title()
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2012-01-23
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多