Wagtail 自定义文档模型

Wagtail Custom Document Model

我从这个帖子中了解到https://github.com/wagtail/wagtail/issues/2001

您可以自定义 Wagtail 文档模型,就像您可以自定义图像模型一样,以向其添加额外的字段。我找不到有关如何执行此操作的任何文档。如果有人对从哪里开始有任何建议,那就太好了。我是鹡鸰的新手,非常感谢任何帮助。

谢谢!

自定义文档模型的实现方式与 custom image model 类似。要添加您自己的文档模型(我们称之为 CustomDocument),您应该执行以下操作:

  1. 创建一个继承自 wagtail.wagtaildocs.models.AbstractDocument 的模型。应该是这样的:

    class CustomDocument(AbstractDocument):
        # Add your custom model fields here
    
        admin_form_fields = (
            'title',
            'file',
            'collection',
            'tags'
            # Add your custom model fields into this list,
            # if you want to display them in the Wagtail admin UI.
        )
    
  2. 注册一个 post_delete 信号处理程序,以便在数据库中删除文件记录后从磁盘中删除文件。它应该是这样的:

    # Receive the post_delete signal and delete the file associated with the model instance.
    @receiver(post_delete, sender=CustomDocument)
    def document_delete(sender, instance, **kwargs):
        # Pass false so FileField doesn't save the model.
        instance.file.delete(False)
    
  3. 设置 WAGTAILDOCS_DOCUMENT_MODEL 设置以指向您的模型。示例:

    `WAGTAILDOCS_DOCUMENT_MODEL = 'your_app_label.CustomDocument'` 
    

只是对@m1kola 回答的小修正:您不需要注册 post_delete 信号。 Wagtail 已经做到了:

def post_delete_file_cleanup(instance, **kwargs):
    # Pass false so FileField doesn't save the model.
    transaction.on_commit(lambda: instance.file.delete(False))


def register_signal_handlers():
    # in example above it returns CustomDocument model and register signal 
    Document = get_document_model() 
    post_delete.connect(post_delete_file_cleanup, sender=Document)

查看他们的github