Reputation: 29589
On Django Forms, how do I specify a default value for a field if the user leaves it blank? Initial sets an initial value, but the user can delete this.
Upvotes: 11
Views: 9317
Reputation: 91
WallyBay's answer works for me. (+adding my experience)
If you leave the form field empty, None value will be passed. you can check this by printing out from.cleaned_data().
But, in my case, None value wasn't replaced with the Model's default value.
I tested by creating objects in the shell('python manage.py shell') passing 1)None value and 2)empty parameter.
My Model:
class Cart(models.Model):
total_amount = models.DecimalField(decimal_places=2, max_digits=1000, default=1, blank=True, null=True)
quantity = models.IntegerField(default=1, blank=True)
note = models.CharField(max_length=300, default='nothing to mention')
summery = models.TextField(blank=False, null=True)
event_won = models.BooleanField(default=False)
My Form:
class CartForm(forms.ModelForm):
summery = forms.CharField()
total_amount = forms.DecimalField(required=False)
quantity = forms.IntegerField(initial=20)
note = forms.CharField(widget=forms.TextInput(attrs={"placeholder":"write a note"}))
class Meta:
model = Cart
fields = [
'summery',
'total_amount',
'quantity',
'note'
]
1) create the object by passing None value.
Cart.objects.create(total_amount=None)
Result: Default value didn't apply. The total_amount is Null(None).
2) create the object without passing any.
Cart.objects.create()
Result: default value worked. total_amount is 1.
When I delete null=True option for the total_amount in the Model class, it gives me an error 'NOT NULL constraint failed'
Upvotes: 0
Reputation: 156
If you're using a ModelForm
simply follow Dan's advice.
If however you're simply using a Form
then you may have to specify how to deal with validation. Example Documentation
class YourForm(forms.Form):
...
def clean_field(self):
data = self.cleaned_data['field']
if not data:
data = 'default value'
return data
Upvotes: 13
Reputation: 6318
Set a default value in the model.
class YourModel(models.Model):
this_field = models.TextField(default="default_value")
Upvotes: 6