Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Django models field is empty, set value to the Default value

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?

like image 927
Girrafish Avatar asked Jul 05 '17 22:07

Girrafish


People also ask

Are Django fields NULL by default?

null. If True , Django will store empty values as NULL in the database. Default is False .

What does blank true in Django mean?

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.

What is NULL and blank in Django models?

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.


1 Answers

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.

like image 161
hansTheFranz Avatar answered Oct 05 '22 23:10

hansTheFranz