Whenever the user doesn't add a value, I need my Django models to replace the otherwise empty field with the value set in default
.
My models looks like this:
not_before = models.TimeField(blank=True, null=True, default='00:00:00')
max_num_per_day = models.IntegerField(blank=True, null=True, default=0)
I tried every combination of null
, blank
and default
but no matter what I do, the fields gets replaced by null
instead of '00:00:00'
and 0
.
Is there anyway I can force it to the default
value whenever the field is empty?
null. If True , Django will store empty values as NULL in the database. Default is False .
If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value . If a field has blank=False, the field will be required.
you can set up your form with a default function like:
class YourForm(forms.Form):
.....
def clean_field(self):
data = self.cleaned_data['not_before']
if not data:
data = '00:00:00'
or write a function in your model like:
class Molde(models.Model):
not_before = models.TimeField(blank=True, null=True, default='00:00:00')
def time(self):
if self.not_before:
return self.not_before
else:
return '00:00:00'
In this case you would call the function instead of the model field itself. You can also take a look at this.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With