[Django]-How to assign default value to Django model Integerfield, while related FormField is optional?

23๐Ÿ‘

i you want field to be optional โ€“ just leave second definition in the model and do not add anything in the form definition:

class Invoice(models.Model):
    expireDays = models.PositiveSmallIntegerField(default=1, blank=True, null=True)

class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice

update, so in case there is no value set, use 1 as the field value:

class InvoiceForm(forms.ModelForm):

    def clean_expireDays(self):
        exp_days = self.cleaned_data.get('expireDays')
        if exp_days is None:
            return self.fields['expireDays'].initial
            # above can be: return 1
            # but now it takes value from model definition
        else:
            return exp_days

    class Meta:
        model = Invoice
๐Ÿ‘คJerzyk

Leave a comment