I’m trying to auto populate (update) a datefield, when a certain choice is chosen by the user:
following is my code
class Tasks(models.Model):
name = models.CharField(max_length=255)
boat = models.ForeignKey(Boat, on_delete=models.CASCADE, null=True, blank=True)
assigned_to = models.ForeignKey(Technician, on_delete=models.SET_NULL, null=True, blank=True)
created_by = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True, blank=True)
created_date = models.DateTimeField(default=datetime.now, blank=True)
completed_date = models.DateField(null=True, blank=True)
CONDITION_STATUS = (
('c', 'Completed'),
('p', 'Pending'),
('i', 'Incomplete'),
)
status = models.CharField(
max_length=1,
choices=CONDITION_STATUS,
blank=True,
default='i',
)
as you can see, I want, when a technicain
choses completed
choice, it to automatically trigger an insert on datetime to the completed_date
field.
I’m trying this with a clean method in my forms.modelForm class:
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = (
'created_by',
'created_date',
'completed_date',
**....
)
def clean(self):
cleaned_data = super().clean()
if self.errors:
return cleaned_data
choice = cleaned_data.get('status')
if choice == 'c':
cleaned_data['completed_date'] = datetime.date.today()
return cleaned_data
**....
however it seems it is not working, and what is the best approach to it, or can point me to the right direction
thanks.