mardi 18 août 2020

How to update a DateTimeField ONLY WHEN a BooleanField is checked from False to True?

# models.py
class Appointment(models.Model):
    # not including some model fields and instead focusing on the model fields that are of concern
    records_sent = models.BooleanField(default=False)
    record_sent_date = models.DateTimeField(blank=True, null=True)
    records_received = models.BooleanField(default=False)
    record_received_date = models.DateTimeField(blank=True, null=True)


# views.py
class AppointmentUpdateView(UpdateView):
    model = Appointment
    fields = ['records_sent', 'records_received']

    def form_valid(self, form):
        """ Update sent/received datetimes to current time
        when sent/received is checked from false to true.
        """
        appointment = self.object
        if form.instance.records_sent:
            appointment.records_sent_date = timezone.now()
        if form.instance.records_received:
            appointment.records_received_date = timezone.now()
        return super().form_valid(form)

My main concern has to do with my if-statement logic in my Class View's form_valid method. Currently, if my BooleanFields are checked True via POST request, the timezone updates to now(), which is fine. But let's say I set records_sent=True on 2:00 pm. If I set records_received=True on 4:00 pm, records_sent ALSO updates its time to 4:00 pm because the POST request sent records_sent AND records_received = True in the form, subsequently triggering the if-statement again when it should be only applying to records_received.

How can I make it so that datetime.now() triggers ONLY when booleanfield is set from False to True, rather than having it also trigger from True to True?

Aucun commentaire:

Enregistrer un commentaire