Daily Dev Notes 2024/06/10

OK, made some good progress tonight. Refactored the post and posts contexts for all the views, and then had to update the tests to match.

Then I had my first crack at implementing template hierarchy. Again, inspired by the old WordPress template files.

With a little help from my AI friends, and of course the Django docs, I came up with the below code which does exactly what I want.

from django.template.loader import TemplateDoesNotExist, select_template

...

def post_detail(request: HttpRequest, path: str) -> HttpResponse:

...

    template_names: list[str] = [
        "djpress/single.html",
        "djpress/index.html",
    ]
    template = select_template(template_names)

    if not template.template.name:
        msg = "Template not found"
        raise TemplateDoesNotExist(msg)

    ...

    return render(
        request=request,
        context={"post": post},
        template_name=template.template.name,
)

I implemented similar heirachy for the date-based archives, category, and author views too, and also the home/index page.

    template_names: list[str] = [
        "djpress/home.html",
        "djpress/index.html",
    ]
    template_names: list[str] = [
        "djpress/author.html",
        "djpress/index.html",
    ]
    template_names: list[str] = [
        "djpress/category.html",
        "djpress/index.html",
    ]
    template_names: list[str] = [
        "djpress/archives.html",
        "djpress/index.html",
    ]

Nice win!