# Programmatically creating Documents in Wagtail

It's very easy to manage PDFs, spreadsheets, Microsoft Word documents and so on through [Wagtail](https://wagtail.io/)'s admin interface. What if you generated such documents on-the-fly, and wanted them to be available in the [Documents](https://docs.wagtail.io/en/stable/editor_manual/documents_images_snippets/documents.html) section of the Admin interface? I was faced with such a situation, and this is how I did it ...

```python
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](https://www.twitter.com/pieterclaerhout)'s approach in [Programatically importing images in Wagtail](https://www.yellowduck.be/posts/programatically-importing-images-wagtail/).
