How do I check if today’s date matches a date created in a Django application?

Asked

Viewed 417 times

0

I have an app that gets the day of the week and the time when an event should occur.
In addition, it also receives the period of time that people must confirm presence.
My model goes below:

def validar_apenas_um(obj):
    model = obj.__class__
    if model.objects.count() > 0 and obj.id != model.objects.get().id:
        raise ValidationError("Você só pode adicionar um horário")

class ModelPresenca(models.Model):
    DIAS = (
        ('Domingo', 'Domingo'),
        ('Segunda', 'Segunda'),
        ('Terça', 'Terça'),
        ('Quarta', 'Quarta'),
        ('Quinta', 'Quinta'),
        ('Sexta', 'Sexta'),
        ('Sábado', 'Sábado'),
    )
    dia = models.CharField('Dia da Pelada', max_length=10, help_text='Escolha o dia da pelada', choices=DIAS)
    hora_pelada = models.TimeField('Horário da pelada (ex: 19:30)', help_text='Hora em que sua pelada é realizada')
    dias_antecedencia = models.PositiveIntegerField('Dias antecedência',
                                                    default=1,
                                                    validators=[MinValueValidator(1), MaxValueValidator(6)],
                                                    help_text='Em quantos dias de antecência os peladeiros devem '
                                                              'marcar presença')

I have done some things aside that I haven’t put together in my Django app, because I don’t know if it’s the best way.
For example, I think to take the day of the week chosen by the user and convert to integer (0 to 6) through the function "weekday", so that the function dia_da_pelada receives this number, as well as the time chosen (Timefield) by the user, returning, thus, the date in the format %Y:%M:%D %H:%M.
In turn, the function "start_date" will receive the number of days and the date of the event to be able to return the opening to the confirmation in advance:


"""
    Converting the day of the week (string) to an integer because the date object receives numbers for year, month, and day.  
"""
def dia_semana(dia):
    switcher = {
        'Segunda': 0,
        'Terça':   1,
        'Quarta':  2,
        'Quinta':  3,
        'Sexta':   4,
        'Sábado':  5,
        'Domingo': 6,
    }

    return switcher.get(dia)

"""
    Day of the event.  
"""
def dia_pelada(dia, hora=' 19:30'):

    data_atual = datetime.today()
    dia_datetime = date(data_atual.year, data_atual.month, data_atual.day)

    if data_atual.weekday() > dia:
        delta_dia = abs(dia - data_atual.weekday()) + 1
    else:
        delta_dia = abs(dia - data_atual.weekday())
    print(delta_dia)
    dia_datetime += timedelta(days=delta_dia)
    dia_string = '{}-{}-{}'.format(dia_datetime.year, dia_datetime.month, dia_datetime.day)
    # to see how to convert TimeField to String
    dia_string = dia_string + hora
    return datetime.strptime(dia_string, '%Y-%m-%d %H:%M')

def data_inicio_confirmar(num, data_pelada):
    hora_inicio = ' 00:00:01'
    data_inicio = '{}-{}-{}'.format(data_pelada.year, data_pelada.month, data_pelada.day-num)
    data_inicio = data_inicio + hora_inicio
    return data_inicio

I’m thinking of the following algorithm to finish this part, but I don’t know how to make this repeat every week without needing the user to always add the same information.
If anyone can help me or show me a way, I’d appreciate it.

week_d = dia_semana('Sexta') 
event_d = dia_pelada(week_d)
conf_d = data_inicio_confirmar(1, event_d) 


n = datetime.now()
t_str = '{}-{}-{}'.format(n.year, n.month, n.day)
t_hour = ' {}:{}'.format(n.hour, n.minute)
today = t_str + t_hour
datetime.strptime(today, '%Y-%m-%d %H:%M')
if (conf_d == today) and (today < event_d):
    # call my formulary to confirm presence
else:
    # another thing        

  • 1

    take a look at this link https://answall.com/questions/327545/comparar-datas-em-python, this is what you’re looking for?

  • Hello @Renan, thank you so much for the feedback! But that’s not it. It would be something like the linux crontab, where I could schedule events at the times mentioned above. It would leave open a form at the established time until the day and time the event will take place, as a attendance list. I was seeing that this can be done with Celery. I mean, I posted my question in Stackoverflow in English and they answered me like this. Anyway, I thank you for your help!

  • 1

    @Thales, nothing comes to mind that can help you directly at the moment, but I have an idea of what can serve you, and it’s quite simple, you quoted the crontab and I think you could use it just for that, how? you can schedule the maguina to send a request via url to Jango, where you would set it so that it reacted in a certain way when it received this say "warning"It’s just a suggestion, but if I get any light on what might help you or need you to explain my above idea, I’ll be right back. I imagine the Python thread can also help

  • @Guilhermefrançadeoliveira, thanks for your attention! Yeah, I’ve thought about doing it for Crontab. Maybe I’ll try something like that. Thank you if you can give me another idea. Thank you again!

  • My answer is detailed in stackoverflow in English: link to question

  • My answer is detailed in Stackoverflow in English: link to the solution I found for myself

Show 1 more comment

1 answer

1


A solution, and you’ve already mentioned, is to use Celery & Rabbitmq. I recently developed a streaming solution that involves making somewhat high processing cost calculations. My choice was to create tasks with Celery and Rabbitmq, you have here an example. Additionally and already included in this, allows also to create periodic tasks, 10 in 10 min. every day, weeks etc. share example and configuration prints in Django admin, I think this is what you need.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

A part of my example:

How a new task is created via another function.... com .delay()

 validate_errors.delay()

And this call from the function with the . delay, will send a message to Broker, Rabbitmq, which is to process, the filename for example and the id of the task, the available Workers will process the upload as soon as possible.... this is a summary of the flow...any additional issue disposes.

@task
def validate_errors():
    cpu = psutil.cpu_percent()
    if cpu < 60:
        return 'Done ERRORS validation validate_errors()'
    return 'CPU Busy validate_errors()'

NOTE: You can use another Roker, Redis for example.

  • thanks for the reply and attention! Excuse me also for the delay in responding! I am traveling these days, but soon I will return. As this should be the way, I will mark your answer as the right one as soon as I can. And thank you for being willing to help. I’ll ask if I need!

Browser other questions tagged

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