Daily Dev Notes 2024/06/08

Still working on the template tags for DJ Press. I realised that in taking inspiration from WordPress, I'm unnecessarily complicating things in the templates. So I'm now moving some of the logic back to the views in order to simplify things.

Ultimately, the views will return either a collection of posts or a single post. Sometimes a collection of posts will only contain one post, which is different to a single post. A single post is exactly that - it is when a single post has been requested, and a single post has been returned by the view. A collection of pots is for all other use cases - e.g. the collection of posts in a specific category, or the collection of posts by a single author, or any of the date-based views. Sometimes these collections of posts may only have a single post, but you still want to display that one post the same way as you would if being sent more than one.

For example, when retrieving the posts in a particular category, you probably only want to show the truncated content, and perhaps less metadata, and you wouldn't want to show a comment form or anything like that. Even if there was only a single post in the category, you would still want to show it in the same way. However, when selecting a single post, that's when you want to have a different way of displaying it. You'd want to show the full content, a comment form perhaps, additional metadata, probably a post heading without a clickable link, etc.

If this all sounds obvious, you're right - it is. But the previous approach I had just implemented was to always return a collection of posts, even if just a single post was being requested. This made implementing a simple template like the WordPress Classic template possible, but at the cost of complexity in other areas. For example, you then needed additional logic in the template to differentiate between a single post and a collection of posts that only contained one post.

I didn't like this approach so have gone back to returning either a collection of posts, or a single post in the views. To help this, I also implented some testing so that any view that's meant to return a collection of posts can be tested to ensure the posts object always contains an interable object, which could be a Page from the paginator or queryset of Posts.

My AI friend suggested the following code, which I adapted slightly for my use-case:

from collections.abc import Iterable

def is_iterable(obj):
    return isinstance(obj, Iterable)

Simple.

No GitHub or PyPi links - will hold off pushing changes until I'm sure of the approach.