omid jahadi
omid jahadi

Reputation: 161

How to preprocess data for django template in the class based view

I have a database of ads and want to show them in a template. The datetime of these ads are in the milliseconds since epoch format and must be converted to the 'a time ago' format. I wrote this code in views.py and working well for just one ads. How can I change that to working for all ads in database?

class crawler(generic.ListView):
    paginate_by = 12
    model = models.Catalogue
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        for cat in models.Catalogue.objects.all():
            if cat.source_id == 3:
                date = float(cat.datetime)
                d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
                d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f')
                now = datetime.datetime.now()
                time_ago = timeago.format(d_datetime, now, 'fa_IR')
            context['time_ago'] = time_ago
        return context

How can I write this code in script?

index.html:

{% for Catalogue in catalogue_list %}
    <h4 class="card-title mt-3" dir="rtl" style="text-align:right;">{{ Catalogue.title }}</h4>
    <br>{{ Catalogue.source }}
    <div class="card-footer" dir="rtl" style="text-align:right">
        <small id="datetime">{{ time_ago }}</small>
    </div>
{% empty %}
    <p>There are no ads in database.</p>
{% endfor %}

Upvotes: 0

Views: 302

Answers (2)

yvesonline
yvesonline

Reputation: 4837

I'd recommend using the built-in timesince filter.

<small id="datetime">{{ Catalogue.datetime|timesince }}</small>

Upvotes: 3

IVNSTN
IVNSTN

Reputation: 9299

You could provide a list/dict of preprocessed objects instead of objects + some values which can be hard to associate to each other, however my suggestion - since transformation is trivial and does not require additional DB queries - is to make a custom template filter:

@register.filter
def time_ago(value):
    # no changes to your code except cat.datetime -> value
    date = float(value)
    d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
    d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f')
    now = datetime.datetime.now()
    time_ago = timeago.format(d_datetime, now, 'fa_IR')
    return time_ago 

and use it in the template like

<small id="datetime">{{ Catalogue.datetime | time_ago  }}</small>

maybe surrounded by if cat.source_id == 3 if needed.

And remove def get_context_data from the view.

Upvotes: 1

Related Questions