W tail自定义文档模型

时间:2017-04-13 09:16:03

标签: wagtail

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

您可以像图像模型一样自定义Wagtail文档模型,以便为其添加额外的字段。我无法找到的是有关如何执行此操作的任何文档。如果有人有任何关于从哪里开始的建议,这将是伟大的。我不知所措,所以任何帮助都非常感激。

谢谢!

2 个答案:

答案 0 :(得分:6)

自定义文档模型可以与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'` 
    

答案 1 :(得分:0)

只是对@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