Victor Miti
import this – a blog about python & more

import this – a blog about python & more

Programmatically creating Documents in Wagtail

Programmatically creating Documents in Wagtail

Victor Miti's photo
Victor Miti

Published on Dec 31, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

It's very easy to manage PDFs, spreadsheets, Microsoft Word documents and so on through Wagtail's admin interface. What if you generated such documents on-the-fly, and wanted them to be available in the Documents section of the Admin interface? I was faced with such a situation, and this is how I did it ...

import os
from datetime import datetime
from django.core.files.base import File
from wagtail.documents.models import Document

def create_wagtail_document(f, title):
    """
    programmatically create a wagtail document which will
    automatically be available in the Documents section of wagtailadmin
    """
    doc_file = File(open(f, "rb"), name=os.path.basename(f))
    doc = Document(
        title=title,
        file=doc_file,
    )
    doc.save()

f = os.path.join("your_file")
today = datetime.now().strftime("%Y-%b-%d-%a")
now = datetime.now().strftime("%-I:%M%p")
doc_title = f"My awesome document created on {today} at {now}"
create_wagtail_document(f, doc_title)

The solution was inspired by Pieter Claerhout's approach in Programatically importing images in Wagtail.

 
Share this