from django.core.management.base import BaseCommand, CommandError
from datetime import datetime
from pathlib import Path
from textwrap import dedent
class Command(BaseCommand):
help = "Create a new blog post markdown file"
def add_arguments(self, parser):
parser.add_argument(
"--title",
default="Enter Title Here",
help="Post title",
)
parser.add_argument(
"--description",
default="",
help="Post description",
)
parser.add_argument(
"--category",
default="news",
help="Post category",
)
parser.add_argument(
"--author",
default="nobo",
help="Author name",
)
def handle(self, *args, **options):
title = options["title"]
description = options["description"]
category = options["category"]
author = options["author"]
today = datetime.today().strftime("%Y-%m-%d")
output_dir = Path("content/blog")
output_dir.mkdir(parents=True, exist_ok=True)
filename = output_dir / f"{today}.md"
if filename.exists():
raise CommandError(f"File already exists: {filename}")
content = dedent(
"""\
---
title: {title}
description: {description}
date: {today}
categories:
- {category}
authors:
- {author}
---
A New Post
"""
).format(
title=title,
description=description,
today=today,
category=category,
author=author,
)
filename.write_text(content, encoding="utf-8")
self.stdout.write(self.style.SUCCESS(f"Created {filename}"))