How can I add a default value for DateField in a model?

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.

exp = models.DateField('exp date', blank=True, null=True)

Im not sure if more of my code will be needed or if what im asking is possible but any help would be appreciated. Even a link to some material on something similar to this!

There are multiple ways of achieving this functionality.

One option is to handle this in the JS of your view, so that when a user selects a particular option for type you can automatically fill in the exp date.

Another option would be not to display the exp field in the form where the users is entering the type. Then in your save method, automatically fill in what the exp should be.

Back to Top