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

Whenever the user doesn't add a value, I need my Django models to replace an otherwise empty field with the value set to default

.
My models look 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've tried every combination of null

, blank

and default

, but no matter what I do, the fields are replaced with null

instead of '00:00:00'

and 0

.

default

Is there anyway I can force its value whenever the field is empty?

+3


source to share


3 answers


from what I understood from your question, you just want to set it as default. you can use: https://code.djangoproject.com/ticket/6754

not

not_before = models.TimeField(blank=True, null=True, default='00:00:00')

      



instead

import datetime
not_before = models.TimeField(default=datetime.time(0,0))
max_num_per_day = models.IntegerField(default=0)

      

+3


source


you can customize your form with the 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 are calling the function instead of the model field itself. You can also take a look at.

Hope it helps.

+2


source


You seem to be using ModelForm to grab data from the user.

In this case, Sasuke's solution won't work. First, you need to set the parameter required

to False

in the form fields so that you stop sending "This field is required" messages. However, you will see errors when you save the form. Even if your model instance is initialized with a default value, the form will replace it with None

because there is an existing field in the form corresponding to the field in the model, and its value is None

.

My solution is to override the values ​​in the model instance before storing them:

model_instance = myform.save(commit=False)
if not model_instance.not_before:
    model_instance.not_before = '00:00:00'
if not model_instance.max_num_per_day:
    model_instance.max_num_per_day = 0
model_instance.save()

      

0


source







All Articles