'How can I add a conditional within my model that changes a model field based on a previous fields value?

Using Django/python. So I have a 'food' model that is taking multiple user inputs, one of which is 'type' and has the options of 'fresh' and 'pantry'.

Another is a DateField that represents an expiration date.

What i want is that when the user selects 'fresh' in the type field, I want the default date to be todays date + 3 days.

If the user selects pantry then I want to use the date that is entered into my food model by the user.

This is my Model.

TYPE = (
    ('Fresh Produce', 'Fresh'),
    ('Pantry', 'Pantry')
)

OPTION = (
    ('P', 'Pick-Up'),
    ('D', 'Delivery')
)

class Grub(models.Model):
    item =  models.CharField(
        max_length=50,
        blank = True,
        null = True
       )
    type = models.CharField(
        max_length = 50,
        choices = TYPE,
        default= TYPE[0][0]
        )
    exp = models.DateField(
        'exp date',
         blank = True,
         null = True
        )
   
    desc =  models.TextField(
        max_length=250,
         blank = True,
         null = True
         )
    price = models.IntegerField(
         blank = True,
         null = True
        )
    option = models.CharField(
        max_length=1,
        choices=OPTION,
        default=OPTION[0][0]
        )
    location = models.CharField(
        max_length=200,
         blank = True,
         null = True
        )
    user = models.ForeignKey(User,  on_delete=models.CASCADE)
    url = models.FileField(
        max_length=200,
        blank = True,
        null = True
        )

    
    def __str__(self):
       return self.item
   

    def get_absolute_url(self):
        return reverse('detail', kwargs={'grub_id': self.id})

And this is kinda what I was thinking but im not sure where to put it or how to implement it.

if type == 'Fresh':
   exp == Date.now() + timedelta(days=3)

This is my form_valid method, which I would like to override.

def form_valid(self, form):
        form.instance.user = self.request.user
        if form.instance.type == 'Fresh':
            form.instance/exp == Date.now()+timedelta(days=3)
        super().form_valid(form)


Solution 1:[1]

try overriding save method with something like this

def save(self, *args, **kwargs):
    if not self.exp:
        if self.type == 'Fresh':
            self.exp = Date.now()+timedelta(days=3)
    super().save(*args, **kwargs)

just verify if Date.now() is properly defined

or for form_valid override return the super.form_valid(form)

def form_valid(self, form):
    form.instance.user = self.request.user
    if form.instance.type == 'Fresh':
        form.instance/exp == Date.now()+timedelta(days=3)
    return super().form_valid(form)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1