# 5 design patterns used in my new habit tracker app

> Source: <https://belderbos.dev/blog/python-patterns-django-habit-tracker/>
> Published: 2026-09-06 00:00:00+00:00

# 5 design patterns used in my new habit tracker app

*Shipping fast with AI but don't fully trust the code? I help developers 1:1 turn AI-built apps into something they understand and own. [How it works →](/coaching/#own-project)*

There are plenty of habit trackers, but I wanted to build mine with constraints, a calendar view and habit streaks. So I built [commitgraph](https://commitgraph.app): a small Django + HTMX app. Here are five Python design and testing patterns from building it.

## 1. Pure functions

Streak counting and calendar shading live in two plain modules. They take dates and return values. And work independently from Django, the database, or the user. That makes them easy to test.

``` python
# streaks.py
from datetime import date, timedelta

def longest_streak(dates: list[date], is_due=lambda _: True) -> int:
    days = set(dates)
    if not days:
        return 0
    best = run = 0
    cur, last = min(days), max(days)
    while cur <= last:
        if is_due(cur):
            run = run + 1 if cur in days else 0
            best = max(best, run)
        cur += timedelta(days=1)
    return best
```

Thanks to this boundary the streak logic is easy to unit test; no database nor user are needed.

Another example: each calendar cell gets a shade from how much you completed that day. It is tempting to compute that in the template. Instead, I turned it into a helper function:

``` php
# calendars.py
def shade(completed: int, active: int) -> str:
    if active == 0 or completed == 0:
        return "bg-[var(--g0)] text-muted"
    frac = completed / active
    if frac >= 1:
        return "bg-[#a84420] text-white"
    if frac >= 0.6:
        return "bg-[#d97a4e] text-[#3a1c0e]"
    return "bg-[#f6ddc9] text-[#3a1c0e]"
```

`assert shade(5, 5).endswith("text-white")` is again easy to test and it's reusable in different parts of the app.

## 2. A schedule is a 7-bit integer

Claude suggested this nifty approach: a habit runs on a subset of weekdays. That is seven yes/no answers, which fit cleanly into a single 7-bit integer.

```
class Habit(models.Model):
    ALL_DAYS = 0b1111111   # every day
    WEEKDAYS = 0b0011111   # Mon-Fri (weekday() 0-4)
    due_days = models.PositiveSmallIntegerField(default=ALL_DAYS)

    def is_due_on(self, day: date) -> bool:
        return bool(self.due_days & (1 << day.weekday()))
```

No join table, no seven boolean columns. Adding "weekends only" is a new constant, not a migration.

The `is_due_on` one-liner treats `due_days` as a **7-bit binary calendar**, one switch per weekday, ordered right-to-left from Monday (0) to Sunday (6).

`day.weekday()` gives 0-6 (Mon-Sun). `1 << day.weekday()` puts a single bit at that day's position, and `& self.due_days` is non-zero only if the habit is scheduled that day. `bool()` turns that into `True`/` False`.

## 3. Let the standard library build the month grid

A month grid can be tricky: leading blanks, trailing blanks, weeks that straddle two months. Python's `calendar` module already knows all of it.

``` python
import calendar

for week in calendar.Calendar(firstweekday=0).monthdatescalendar(year, month):
    for day in week:
        if day.month != month:
            ...  # a padding cell from the previous or next month
```

`monthdatescalendar` returns real `date` objects, one clean list of weeks; no need to write any logic around how many days April has.

## 4. A query vocabulary on the model

"Active habits" and "habits active on a given day" show up everywhere. Rather than repeating the filters in every view, I named them on a custom `QuerySet` so they are chainable:

``` python
class HabitQuerySet(models.QuerySet):
    def active(self):
        return self.filter(archived_at__isnull=True)

    def active_on(self, day: date):
        return self.filter(
            Q(start_date__lte=day)
            & (Q(archived_at__isnull=True) | Q(archived_at__date__gte=day))
        )

class Habit(models.Model):
    objects = HabitQuerySet.as_manager()
```

Now `Habit.objects.filter(user=u).active()` is very readable and the relatively complex `Q` expressions are abstracted into the model.

## 5. "Done and due" is set algebra

The Today screen needs habits that are due today and not yet checked off. Two sets and one operator.

```
due_ids = {h.id for h in habits}
done_ids = set(
    HabitCompletion.objects
    .filter(habit__user=user, date=day)
    .values_list("habit_id", flat=True)
) & due_ids
```

The intersection drops any completion for a habit that is not due today, so a spurious record can't inflate the count. The logic is the math, not a nest of `if` statements.

Here is a REPL snippet that demonstrates how set intersection (`&`) filters down to only the elements present in both sets:

```
>>> due_ids = {10, 11, 12, 13}      # Habits scheduled for today
>>> completed_ids = {11, 13, 99}    # Logged completions (99 is a stray record)

>>> # The '&' operator keeps ONLY IDs present in BOTH sets
>>> done_today = completed_ids & due_ids
>>> print(done_today)  # 10, 12 and 99 are dropped because they are not in both sets
{11, 13}
```

I have also seen this used in RBAC logic to cross-check user roles with endpoint permissions. The intersection of the two sets is the effective permissions a user has.

## Keep reading

- [Build the Simplest Thing That Works](/blog/build-the-simplest-thing-that-works/)
- [Unsubscribe links without a login: Django signing](/blog/unsubscribe-without-login-django-signing/)
- [Learning Rust Made Me a Better Python Developer](/blog/rust-made-me-a-better-python-developer/)

The thread running through all five patterns: when a piece of logic doesn't strictly need the database or a dependency, stick to this boundary. Fetch your primitive values, do the math in plain Python, so it's more testable in isolation.

What is one function in your Django views that would be much easier to trust and test if you decoupled it?
