'Default value in Django Model
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?
Solution 1:[1]
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
Solution 2:[2]
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)
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alessio Balderi |
Solution 2 | David Lu |
Solution 3 | Abdelrahman Moustafa |