Mauricio Kalfelz
Mauricio Kalfelz

Reputation: 79

How to trigger an event on selection in Django?

Whenever the SAIDA_CHOICES is "Sim" it does not do anything, but when it is "Não", that gives yes and it stores in the database Checkout with datatimenow.

However when I execute the code below being in Sim or Não it always stores the checkout:

SAIDA_CHOICES = (
    ('Não', 'Não Pago'),
    ('Sim', 'Pago')
    )

class MovRotativo(models.Model):
    checkin = models.DateTimeField(auto_now=True, blank=False, null=False,)
    checkout = models.DateTimeField(auto_now=True, null=True, blank=True)
    email = models.EmailField(blank=False)
    placa = models.CharField(max_length=7, blank=False)
    modelo = models.CharField(max_length=15, blank=False)
    valor_hora = models.DecimalField(
         max_digits=5, decimal_places=2, null=False, blank=False)
    pago = models.CharField(max_length=15, choices=PAGO_CHOICES)
    chk = models.CharField(max_length=15, choices=SAIDA_CHOICES)

     def saida(self):
        if self.chk == 'sim':
            return self.chk
        else:
            self.checkout = models.DateTimeField(auto_now=True)
            return self.checkout

Upvotes: 1

Views: 366

Answers (1)

ruddra
ruddra

Reputation: 51988

I think you can override the save method of the model so that if the value is not Nao, then it will store the checkout value to current time:

from django.utils import timezone

class MovRotativo(models.Model):
    ...
    checkout = models.DateTimeField(default=None, null=True, blank=True)  # change it to default None
    ... # rest of the fields

    def save(self, *args, **kwargs):
        if not self.chk == 'Sim':
            self.checkout = timezone.now()
        else:
            self.checkout = None
        return super(MovRotativo, self).save(*args, **kwargs)

Upvotes: 1

Related Questions