Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms: default value if user leaves field blank

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.

like image 614
user984003 Avatar asked Feb 06 '13 15:02

user984003


1 Answers

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
like image 117
WallyBay Avatar answered Oct 07 '22 17:10

WallyBay