2
votes

I understand from this thread https://github.com/wagtail/wagtail/issues/2001

that you can customise the Wagtail Document Model, as you can the Image Model, to add extra fields to it. What I can't find is any documentation on how to do this. If anyone has any suggestions on where to start that would be great. I'm new to wagtail so any help much appreciated.

Thanks!

2

2 Answers

7
votes

Custom document model can be implemented in a similar way as a custom image model. To add your own document model (let's call it CustomDocument) you should do the following:

  1. Create a model that inherit from wagtail.wagtaildocs.models.AbstractDocument. Should be something like:

    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. Register a post_delete signal handler to remove a file from your disk once document record deleted in the database. It should be something like this:

    # 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. Set the WAGTAILDOCS_DOCUMENT_MODEL setting to point to your model. Example:

    `WAGTAILDOCS_DOCUMENT_MODEL = 'your_app_label.CustomDocument'` 
    
0
votes

Just small correction to @m1kola's answer: you don't need to register post_delete signal. Wagtail already does it:

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)

See their github