Home > database >  Django - implementation of last changes tracker in HTML file
Django - implementation of last changes tracker in HTML file

Time:03-19

I am looking for a solution that will allow me to create a section in my HTML file with the latest updates in my app. I checked some packages here on djangopackages.org but I am not quite sure which app should I use.

The idea is that if there will be any article added or updated then in the latest updates section the information will appear automatically as: '5 new articles have been recently added' or '2 articles have been updated' or'3 users joined our website'.

In total, I have 4 models (including the user model) in my Django app that I want to track and display updates in my HTML (homepage, TemplateView) file.

What would you recommend?

CodePudding user response:

Not sure if I am taking a too simplistic approach, and perhaps this is not ideal since its not necessarily abstracted to scale, but since you only have 4 models and you have only specified that you want to count new and updated objects, couldn't you just create a list and return that to the template?

With the simple requirements this might make more sense rather than creating a third party dependency.

You can add an updated_at and created_at fields to you models, and then do something like this.

import datetime

week_ago = datetime.datetime.now() - datetime.timedelta(days=7)

models = [Article, User] #Add any models you need to this list

def get_updates(models):
    updates = List()
    for model in models:
        count_new = model.objects.filter(created_at>week_ago).count()
        if count_new:
            list.append(f"{count_new} new {model._meta.verbose_name_plural.title()} have been created in the last week")

        count_updated = model.objects.filter(updated_at>week_ago).count()
        if count_updated:
            list.append(f"{count_updated} {model._meta.verbose_name_plural.title()} were updated in the last week")

    return updates

updates = get_updates(models) #List of the number of new and updated items for each model in the last week

This is a basic example but gives an idea, from which you could extend, reorder, add more info etc.

  • Related