Home > Enterprise >  Default value in Django Model
Default value in Django Model

Time:05-14

I have a model named "Product" and it has an attribute like price, quantity, and remarks. Thru the models.py, if remarks has a property of "null=True", it will return a value "None" but I want it to be a dash(-). If you will be adding a "default='-'" into the remarks column in the model, once its form is created and loaded, it has a dash('-') on it but I want nothing on the form when it's loaded. Do you have any ideas if that's possible?

CodePudding user response:

Maybe you should try a clean method on the form.

def clean_<property>(self):
    property = self.cleaned_data['property']
    if not property:
        return "-"

I haven't tested the code but it should work out

https://docs.djangoproject.com/en/4.0/ref/forms/validation/#cleaning-a-specific-field-attribute

CodePudding user response:

I think you can set the custom initial value of the form

class ProductForm(forms.ModelForm):
    ... fields here ...
    
    def __init__(self, *args, **kwargs):
        ... other code ...
        initial = kwargs.pop('initial', {})
        remark_value = initial.get('remarks')
        initial.update("remarks", "" if remark_value  == "-" else remark_value)
        kwargs['initial'] = initial
        super(ProductForm, self).__init__(*args, **kwargs)

CodePudding user response:

You have more options but here is 2 you can do:

If you want set default="-" you have to override the form __int__() method so the form would looks like

class MyForm(forms.ModelForm):
     def __init__(self, *args, **kwargs):
         
         #creating
         self.fields['your_field'].initial = " "
         
         # updating
         if self.instance.pk:
            self.fields['your_field'].initial = self.instance.your_field

If you do not want set default you have to override the model save() method

class MyModel(models.Model):
    def save(self, *args, **kwargs):
        if not self.your_field:
           self.your_field = "-"
     return super(MyModel, self).save(*args, **kwargs)
  • Related