Show list items filtering by date.Today()

Asked

Viewed 42 times

0

I have a list that I order by position in my models.py, but I have the field start_date I want to use as a validator so that the item is visible or not. But it is not working:

py views.:

from django.shortcuts import render, redirect
from datetime import date
from .models import *
from .forms import *
import requests

def videos_list(request):

    if 'lead_id' in request.session:
        videos = Video.objects.order_by("position").all()
        for video in videos:
            print(video.title)
            if video.start_date < date.today():
                print(True)
                show_video = True
            else:
                print(False)
                show_video = False

        return render(request, 'videos-list.html', {'videos': videos, 'show_video': show_video})

    return redirect('registrations:create_lead')

in the console:

Programe ou seja programado - Episódio 01 True Programa ou seja programado - Episódio 02 True Programe ou seja programado - Episódio 03 False

I understood that at the end of the looping he leaves my variable show_video as False and why mine template empty

video-list.html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        {% for video in videos %}
        {% if show_video %}
        <div>
            <h1>
                {{video.title}}
            </h1>
            <iframe width="560" height="315" src="{{video.url}}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
            <p>
                {{video.description}}
            </p>
        </div>
        {% endif %}
        {% endfor %}
    </div>
</body>
</html>

But I don’t understand how to do it any other way ?

1 answer

3


You need an attribute show_video related to each object Video that you send to the template.

If it wasn’t an object-oriented paradigm, you could create a list, with the value of show_video for each video, and use the zip python in its for inside the template -

    ...
    show_videos = []
    for video in videos:
        print(video.title)
        show_videos.append(video.start_date < date.today()_  # True ou False

And then you’d have to put the logic of going through that list and the list of videos in parallel in the template. Fortunately, that’s not necessary.

Since it’s OO, and Python accepts extra attributes inside the objects, you can also simply embed an extra attribute in the videos, before calling the template:

    ... 
    for video in videos:
        print(video.title)
        if video.start_date < date.today():
            video.show_video = True
        else:
            video.show_video = False
    ...
    # e no template:
    {% if video.show_video %}

But better yet, Python has the properties - which allow properties that can be dynamically calculated with code to work, for those who are using the object, as if they were an attribute.

This means you can put the attribute show_video as a Property in the video class - it is different from an attribute which is an instance of a Field Django - it is not written in the database. And then, you put the same logic that is in your view, right in the model:

from datetime import date

class Video(models.Model):
    ...
    # campos do ORM
    # 
    ...
    @property
    def show_video(self):
          # o valor da expressão já é um boolean, ou seja True ou False:
          return self.start_date < date.today():

How this is the only operation you’re doing on for view, no longer needs it - view is just:

def videos_list(request):

    if 'lead_id' in request.session:
        videos = Video.objects.order_by("position").all()

        return render(request, 'videos-list.html', {'videos': videos})

And in the template, just modify the if as I put up, to catch the field show_video direct from the video object:

    {% if video.show_video %}
  • guy I’m your girlfriend fan, thank you so much for the explanation man, I was banging my head

Browser other questions tagged

You are not signed in. Login or sign up in order to post.